要求
实现一个可以拖拽的div盒子
设置监听事件
- mousedown 点击鼠标,开始拖拽
- mousemove 鼠标移动,拖拽过程中
- mouseup 鼠标抬起,拖拽结束
实现思路
在鼠标点击状态下,比较上次的坐标(x, y) 与这次的坐标(x, y)的差距, 然后重新设置 xxx.style.left和xxx.style.top即可
注意
- xxx.style.left的值是'0px',为了获取到数字,我们需要用parseInt(xxx.style.left)而且这个值还可以是空,所以需要给一个默认值parseInt(xxx.style.left || 0)
- 用position数组来保存上一次的地址
- 监听 document 的mousemove和mouseup事件,而不是监听元素xxx 本身的,否则会出现拖拽幅度过大div会不受控制。 html
<body>
<div id="xxx"></div>
</body>
css
div{
border: 1px solid red;
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
}
*{margin:0; padding: 0;}
js
let dragging = false
let position = null
xxx.addEventListener('mousedown',function(e){
dragging = true
position = [e.clientX, e.clientY]
})
document.addEventListener('mousemove', function(e){
if(dragging === false){return}
const x = e.clientX
const y = e.clientY
const deltaX = x - position[0]
const deltaY = y - position[1]
const left = parseInt(xxx.style.left || 0)
const top = parseInt(xxx.style.top || 0)
xxx.style.left = left + deltaX + 'px'
xxx.style.top = top + deltaY + 'px'
position = [x, y]
})
document.addEventListener('mouseup', function(e){
dragging = false
})