使用js实现鼠标拖动一个盒子移动的实例

代码如下

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .father {
            position: absolute;
            width: 500px;
            height: 300px;
            border: 1px solid #cccccc;
            background-color: #999999;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
        
        .son {
            width: 200px;
            height: 100px;
            background-color: #fff;
            font-size: 25px;
            text-align: center;
            line-height: 100px;
            margin: 10px auto;
            -moz-user-select: none;
            -webkit-user-select: none;
            user-select: none;
        }
        
        .son:hover {
            cursor: move;
        }
    </style>
</head>

<body>
    <div class="father">
        <div class="son">拖拽移动</div>
    </div>
</body>
<script>
    var son = document.querySelector('.son')
    var father = document.querySelector('.father')
    son.addEventListener('mousedown', function(e) {
        var x = e.pageX - father.offsetLeft
        var y = e.pageY - father.offsetTop

        function move(e) {
            father.style.top = e.pageY - y + 'px'
            father.style.left = e.pageX - x + 'px'
        }
        document.addEventListener('mousemove', move)
        document.addEventListener('mouseup', function() {
            document.removeEventListener('mousemove', move)
        })
    })
</script>

</html>

因为要拖动,所以父盒子要加定位,但需要注意的是要使用 absolute 定位,使用 relative 定位的话是有问题的(相对于之前的位置定位)

分为三个事件 , 鼠标按下事件、鼠标拖动事件、鼠标抬起事件。当鼠标按下时获得鼠标在父盒子里面的坐标(x,y),鼠标开始移动的时候用鼠标移动后的坐标减去鼠标在父盒子里面的坐标,把所得的值赋给父盒子的left和top。鼠标抬起时 移除鼠标移动事件。

使用-moz-user-select: none;  -webkit-user-select: none; user-select: none;来禁止选中

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值