美文网首页
JavaScript 可拖曳 div

JavaScript 可拖曳 div

作者: bowen_wu | 来源:发表于2022-10-03 16:31 被阅读0次
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Drag</title>
        <style>
            .drag {
                border: 1px solid red;
                position: absolute;
                top: 0;
                left: 0;
                width: 100px;
                height: 100px;
            }
        </style>
    </head>
    <body>
    <div class="drag"></div>
    <script>
        let dragging = false;
        let position = null;
        const dragEle = document.querySelector('.drag');
        dragEle.addEventListener("mousedown", e => {
            dragging = true;
            position = [e.clientX, e.clientY];
        });
    
        document.addEventListener("mousemove", e => {
            if (!dragging) return;
            const x = e.clientX;
            const y = e.clientY;
            const moveX = x - position[0];
            const moveY = y - position[1];
            const left = parseInt(dragEle.style.left || 0);
            const top = parseInt(dragEle.style.top || 0);
            dragEle.style.left = left + moveX + 'px';
            dragEle.style.top = top + moveY + 'px';
            position = [x, y];
        });
    
        document.addEventListener('mouseup', e => {
            dragging = false;
        })
    </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:JavaScript 可拖曳 div

          本文链接:https://www.haomeiwen.com/subject/tloyartx.html