手写拖曳

85 阅读1分钟

HTML 部分

<div id="box" style="width: 200px;height: 200px;border: 1px solid red;position: absolute;left: 0;top: 0;"></div>

js 部分

 <script>
    let is = false
    let arr = null
    const box = document.querySelector('#box')
    box.addEventListener('mousedown',function(e){
      is = true
      arr = [e.clientX,e.clientY]
    })
    document.addEventListener('mousemove',function(e){
      if(!is) return
      let x = e.clientX
      let y = e.clientY
      const datay = y - arr[1]
      const datax = x- arr[0]
      const left = parseInt(box.style.left || 0)
      const top = parseInt(box.style.top || 0)
      box.style.left = datax + left +'px'
      box.style.top = datay + top  + 'px'
      arr=[x,y]
    })
    document.addEventListener('mouseup',function(e){
      is = false
    })
  </script>

都蛮简单的,如果还有不懂可以私聊或者评论