用js实现可拖动的div

用js实现可拖动的div,其实逻辑很简单,计算鼠标的移动距离然后设置盒子的位置即可
看看效果
在这里插入图片描述
源码


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        body {
            position: relative;
            width: 100vw;
            height: 100vh;
        }

        .box {
            position: absolute;
            width: 400px;
            height: 400px;
            background: skyblue;
        }
    </style>
</head>

<body>
    <div class="box" id='box'>
    </div>

    <script>
        const box = document.getElementById('box')
        let isDown = false
        let mouse = {}
        box.onmousedown = (e) => {
            isDown = true
            box.style.cursor = 'move'
            //保存初始位置
            mouse = {
                startX: e.clientX,
                startY: e.clientY,
                offsetLeft: box.offsetLeft,
                offsetTop: box.offsetTop,
            }
        }

        box.onmousemove = (e) => {
            if (!isDown) {
                return
            }
            //计算偏移位置
            let offsetLeft = mouse.offsetLeft + e.clientX - mouse.startX
            let offsetTop = mouse.offsetTop + e.clientY - mouse.startY

            //设置偏移距离的范围[0,window.innerWidth - 400]
            offsetLeft = Math.max(0, Math.min(offsetLeft, window.innerWidth - 400))
            offsetTop = Math.max(0, Math.min(offsetTop, window.innerHeight - 400))
            
            box.style.left = offsetLeft + 'px';
            box.style.top = offsetTop + 'px';

        }
        //当鼠标滑的太快时,容易移出box,所以在window上监听此事件
        window.onmouseup = () => {
            isDown = false
            box.style.cursor = 'default'
            mouse = null
        }
    </script>

</body>

</html>
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值