Open innerWang opened 5 years ago
//html <div id="box" ></div> //css #box{ border: 1px solid red; width: 50px; height: 50px; position: relative; } //js let dragging = false let position = [] box.addEventListener('mousedown',(e)=>{ dragging = true; position=[e.clientX,e.clientY] }) document.addEventListener('mousemove',(e)=>{ if(!dragging) return let deltaX = e.clientX - position[0] let deltaY = e.clientY - position[1] let left = parseInt(box.style.left) || 0 let top = parseInt(box.style.top) || 0 box.style.left = left + deltaX + 'px' box.style.top = top + deltaY + 'px' position=[e.clientX,e.clientY] }) document.addEventListener('mouseup',(e)=>{ dragging = false })
注意点: 1: 初始未设置top left时为空字符串,使用时需要去掉包含的'px' 2: mousemove 以及 mouseup 需要监听在document上
注意点: 1: 初始未设置top left时为空字符串,使用时需要去掉包含的'px' 2: mousemove 以及 mouseup 需要监听在document上