关于自己实现拖拽的demo

100 阅读1分钟
<div class="drap" />
.drap {
    height: 100px;
    width: 100px;
    background-color: seagreen;
    position: absolute;
}
  const dom = document.getElementsByClassName('drap')[0]
  let l = 0
  let t = 0
  let ifDown = false
  const move = e => {
    const { pageX, pageY } = e
    dom.style.left = pageX - l + 'px'
    dom.style.top = pageY - t + 'px'
  }
  
  dom.addEventListener('mousedown', e => {
    ifDown = true
    const rect = e.target.getBoundingClientRect()
    const { pageX, pageY } = e
    l = pageX - rect.left
    t = pageY - rect.top
  
    document.addEventListener('mousemove', move, false)
  
    document.addEventListener('mouseup', upE => {
      if (ifDown) {
        ifDown = false
        document.removeEventListener('mousemove', move, false)
      }
    })
  }, false)
  /*
      关于为什么需要指定 ifDown 这个变量,其实如上逻辑你会发觉,你每次mousedown这个元素
      document都会绑定一个mouseup事件,所以你每次mouseup都会触发多个回调(包括你之前绑定的)
      所以设置这个变量能保证你只会执行一次回调,因为在第一个回调执行的时候,ifDown被置为了false
  */