美文网首页
可拖拽的div

可拖拽的div

作者: 大脸猫_2e21 | 来源:发表于2019-08-20 16:27 被阅读0次
    <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>``

    相关文章

      网友评论

          本文标题:可拖拽的div

          本文链接:https://www.haomeiwen.com/subject/cgppsctx.html