HTML
<div id="xxx"></div>
CSS
*{margin:0; padding: 0;}
div{
border: 1px solid red;xx
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
}
JavaScript
var dragging = false //是否可拖曳,默认不能
var position = null //记录上一次的坐标,默认空
xxx.addEventListener('mousedown',function(e){ //监听鼠标按下事件,获取xy坐标
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' //把位移的距离放到div上
xxx.style.top = top + deltaY + 'px'
position = [x, y] //把这一次的坐标记录到下一次上
})
document.addEventListener('mouseup', function(e){ //监听鼠标松开事件,不在拖曳
dragging = false
})