鼠标拖动div移动

71 阅读1分钟

鼠标拖动div移动

image.png

**难点在获取style里面的的left和top的值 document.defaultView.getComputedStyle(div)["left"]

<!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>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            width: 200px;
            height: 200px;
            background-color: orange;
            position: absolute;
            left: 200px;
            top: 200px;
        }
    </style>
</head>

<body>
    <div></div>
</body>
<script>
    var div = document.querySelector('div')
    // 鼠标放的地方有e.clientX和e.clientY,
    // 定义鼠标的当前位置
    var currentX = 0;
    var currentY = 0;
    // 定义一个状态,只有为true的时候才监听clientX 和clientY
    var flag = false
    // 鼠标移动的时候,改变原来的left和top的值
    div.onmousemove = function (e) {
        if (flag) {
            // 鼠标移动的时候,偏移了多少
            console.log(e.clientX - currentX, e.clientY - currentY);
            // 获取原来的left top的值,在加上偏移量
            div.style.left = parseInt(document.defaultView.getComputedStyle(div)["left"]) + (e.clientX - currentX) + 'px',
                div.style.top = parseInt(document.defaultView.getComputedStyle(div)["top"]) + (e.clientY - currentY) + 'px'
            // 每一次都要更新当前鼠标所在的位置,不然会乱跑
            currentX = e.clientX
            currentY = e.clientY
        }
    }
    // 当鼠标按下的时候,触发
    div.onmousedown = function (e) {
        flag = true
        // 记录鼠标当前的位置
        currentX = e.clientX
        currentY = e.clientY
    }
    // 鼠标松开的时候,
    div.onmouseup = function () {
        flag = false
    }
</script>

</html>