写一个可拖曳的div

用mouse事件写一个可拖曳的div
1
<div id='app'></div>
1
2
3
4
5
6
7
8
#app{
border: 1px solid red;
height: 100px;
width: 100px;
position: absolute;
top: 0;
left: 0;
}
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
let dragging = false
let position = null

let app = document.getElementById('app')
app.addEventListener('mousedown', e => {
dragging = true
position = [e.clientX, e.clientY]
})

document.addEventListener('mousemove', e => {
if(dragging){
const x = e.clientX
const y = e.clientY
const deltaX = x - position[0]
const deltaY = y - position[1]
const left = parseInt(app.style.left || 0)
const top = parseInt(app.style.top || 0)
app.style.left = left + deltaX + 'px'
app.style.top = top + deltaY + 'px'
position = [x, y]
}
})

document.addEventListener('mouseup', e => {
dragging = false
})