手写可拖拽div

101 阅读1分钟

话不多说直接上代码

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手写可拖曳 div</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            position: relative;
        }
    </style>
</head>

<body>
    <div id="box" class="box"></div>
    <script>
        var dragging = false
        var position = null
        box.addEventListener('mousedown', function (e) {
            dragging = true
            position = [e.clientX, e.clientY]
        })
        document.addEventListener('mousemove', function (e) { // 1. 这里需要监听document,不能只监听div,否则当拖动过快鼠标移动到div之外时会拖动不了
            if (!dragging) return
            const x = e.clientX
            const y = e.clientY
            const dataX = x - position[0]
            const dataY = y - position[1]
            const left = parseInt(box.style.left || 0)
            const top = parseInt(box.style.top || 0)
            box.style.left = left + dataX + 'px' // 2. 这里可以优化成transform,使用 transform 会比 top / left 性能更好,因为可以避免 reflow 和 repaint
            box.style.top = top + dataY + 'px' // 这里同上
            position = [x, y]
        })
        document.addEventListener('mouseup', function (e) {
            dragging = false
        })
    </script>
</body>

</html>

注意:

  1. 注意监听范围,不能只监听 div
  2. 使用 transform 会比 top / left 性能更好,因为可以避免 reflow 和 repaint