js 拖拽drag

该代码示例展示了如何使用HTML、CSS和JavaScript创建一个可拖动的小方块元素,并在拖放过程中改变其透明度。当拖放结束时,小方块会根据鼠标位置调整自身在容器内的位置,同时确保不会超出容器边界。
摘要由CSDN通过智能技术生成
<!DOCTYPE html>
<html lang="en">
<style>
    .smallBox {
        width: 500px;
        height: 500px;
        position: relative;
        background-color: antiquewhite;
        margin: 30px 30px;
    }

    .smallBoxItem {
        position: absolute;
        /* 添加绝对定位,让box相对于页面可移动 */
        top: 30px;
        left: 30px;
        width: 100px;
        height: 100px;
        background-color: red;
    }
</style>

<body>
    <div class="box" draggable="true">
        <div class='smallBox'>
            <div class='smallBoxItem' draggable="true"></div>
        </div>

    </div>
    <script>
        var smallBoxItem = document.querySelector(".smallBoxItem");
        var smallBox = document.querySelector(".smallBox");
        // 开始拖拽
        smallBoxItem.ondragstart = function () {
            // 记录鼠标与盒子之间的距离
            mouse = {
                x: event.offsetX,
                y: event.offsetY
            }
        }

        smallBoxItem.ondrag = function () {
            //拖拽的时候 smallBoxItem透明度改变
            let w = smallBox.offsetWidth - (event.pageX + smallBoxItem.offsetWidth) > 0 ? smallBox.offsetWidth - (event.pageX + smallBoxItem.offsetWidth) : 0
            event.target.style.opacity = w / smallBox.offsetWidth;
        }
        // 拖拽结束
        smallBoxItem.ondragend = function () {
            // 盒子的位置 = 鼠标与页面之间的距离 - 鼠标与盒子之间的距离
            let left = event.pageX - mouse.x
            let top = event.pageY - mouse.y
            //smallBoxItem 拖拽不超过smallBox便捷
            if (left < 0) {
                left = 0
            } else if (left > smallBox.offsetWidth - smallBoxItem.offsetWidth) {
                left = smallBox.offsetWidth - smallBoxItem.offsetWidth
            }

            if (top < 0) {
                top = 0
            } else if (top > smallBox.offsetHeight - smallBoxItem.offsetHeight) {
                top = smallBox.offsetHeight - smallBoxItem.offsetHeight
            }
            smallBoxItem.style.left = left + "px";
            smallBoxItem.style.top = top + "px";
        }
    </script>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值