实现一个可拖拽的div

827 阅读1分钟

1 HTML

<body>
<div id='xxx'></div>
</body>

2 CSS

*{
  padding:0;
  margin:0;
}

#xxx {
  position:absolute;
  border: 1px solid red;
  width: 100px;
  height: 100px;
}

3 JS

let dragging = false;
let position = null;

xxx.addEventListener('mousedown', (e) => {
  dragging = true
  position = [e.clientX, e.clientY]

})

document.addEventListener('mousemove', (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',()=>{
  dragging=false
})

注意点

  • 要用document对'mousemove'进行监听而不是xxx
  • 同理,对'mouseup'的监听也要用document
  • 'xxx.style.left'默认为0px,要用parseInt转为number
  • left和top应给默认值0