js实现拖拽移动元素

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖动demo1</title>
    <style>
        .box {
            width: 20px;
            height: 20px;
            background-color: rgb(247, 196, 196);
            border: 1px solid rgb(252, 153, 153);
            cursor: pointer;
            position: relative;
        }
    </style>
</head>

<body>
    <!-- 拖动的盒子 -->
    <div class="box" id="drag">
        
    </div>
    <script>
        let dragDom = document.getElementById('drag')
        // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
        const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)
        // 鼠标在移动盒子上按下
        dragDom.onmousedown = function (e) {
            console.log('鼠标按下事件')
            dragDom.style.backgroundColor = 'rgb(196, 217, 247)'
            dragDom.style.border = 'rgb(153, 196, 252)'
            dragDom.style.cursor = 'move'

            // 鼠标按下,计算当前元素距离可视区的距离
            const disX = e.clientX
            const disY = e.clientY

            // 获取到的值带px 正则匹配替换
            let styL = null
            let styT = null

            // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
            if (sty.left.includes('%')) {
                styL =
                    +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100)
                styT =
                    +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
            } else {
                styL = +sty.left.replace(/\px/g, '')
                styT = +sty.top.replace(/\px/g, '')
            }

            document.onmousemove = function (e) {
                e.preventDefault() // 移动时禁用默认事件

                // 通过事件委托,计算移动的距离
                const l = e.clientX - disX
                const t = e.clientY - disY

                // 移动当前元素
                dragDom.style.left = `${l + styL}px`
                dragDom.style.top = `${t + styT}px`
            }

            document.onmouseup = mouseUp
        }

        // 鼠标抬起
        function mouseUp() {
            console.log('鼠标抬起事件')
            dragDom.style.backgroundColor = 'rgb(247, 196, 196)'
            dragDom.style.border = 'rgb(252, 153, 153)'
            dragDom.style.cursor = 'pointer'

            document.onmousemove = null
            document.onmouseup = null
        }
    </script>
</body>

</html>

版权声明:本文为weixin_44801790原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。