JavaScript实现一个可以拖拽的div

60 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #move {
      height: 200px;
      width: 200px;
      background-color: aqua;
      position: absolute;
    }
  </style>
</head>
<body>
  <div id="move"></div>
</body>
<script>
  var dragFlag = false
  var position = null
  var move = document.getElementById('move')
  move.addEventListener('mousedown', e => {
    dragFlag = true
    position = [e.clientX, e.clientY]
  })
  document.addEventListener('mousemove', e => {
    if(dragFlag == false) return null
    const x = e.clientX
    const y = e.clientY
    const moveX = x - position[0]
    const moveY = y - position[1]
    const left = parseInt(move.style.left || 0)
    const top = parseInt(move.style.top || 0)
    move.style.left = moveX + left + 'px'
    move.style.top = moveY + top + 'px'
    position = [x, y]
  })
  document.addEventListener('mouseup', e => {
    dragFlag = false
  })
</script>
</html>