可拖拽的div

2019-08-20  本文已影响0人  大脸猫_2e21
<html>

<head lang="en">
  <meta charset="UTF-8">
  <title>拖动</title>
  <style>
    div{
      border: 1px solid red;
      position: absolute;
      top: 0;
      left: 0;
      width: 100px;
      height: 100px;
    }
  </style>
</head>

<body>
  <div id="xxx"></div>
  <script>

    var dragging = false
    var 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] //相对于client移动的位置
      const deltaY = y - position[1] //相对于client移动的位置

      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]  //更新初始的client位置
    })
    document.addEventListener('mouseup', function (e) {
      dragging = false
    })
  </script>
</body>

</html>``
上一篇 下一篇

猜你喜欢

热点阅读