js基础:简单的拖动实例

拖动也总是忘记,简单实现记录一下。demo: https://laputaz.github.io/move/

Demo: https://laputaz.github.io/move/

在这里插入图片描述

相关事件

mousedown / mouseup / mousemove

实现思路

最终效果:目标块在外部容器内随意拖动,不超出。

  1. 将容器设置为相对定位,目标块设置为绝对定位。
  2. 为目标块绑定 mousedown,记录按下鼠标时,鼠标相对于目标块的位置 (diffX / diffY)。
    在这里插入图片描述
  3. 在容器上绑定 mousemove 事件,鼠标移动时,设置目标块的 left 和 top 值
  4. left 的计算(top 同理):
    在这里插入图片描述
  5. left 的最大值:
    在这里插入图片描述

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
let outer = document.querySelector('.outer')
let item = document.querySelector('.item')
let diffX = 0
let diffY = 0
let moving = false

item.addEventListener('mousedown', function (e) {
item.style.cursor = 'move'
moving = true
// 记录按下鼠标时,鼠标相对于目标块的位置
diffX = e.offsetX
diffY = e.offsetY
})

window.addEventListener('mouseup', function (e) {
item.style.cursor = 'default'
moving = false
})

outer.addEventListener('mousemove', function (e) {
if (!moving) return
// 计算 left 和 top
let l = e.x - outer.offsetLeft - diffX
let t = e.y - outer.offsetTop - diffY

// left 不能小于 0
item.style.left = l < 0 ? 0 : l + 'px'
item.style.top = t < 0 ? 0 : t + 'px'

// left 不能超过 outer.clientWidth - item.clientWidth
let DX = outer.clientWidth - item.clientWidth
if (DX < l) {
item.style.left = DX + 'px'
}
let DY = outer.clientHeight - item.clientHeight
if (DY < t) {
item.style.top = DY + 'px'
}
})

以上。