可拖拽div

2019-08-14  本文已影响0人  手劲很大

一个在移动端及PC端都可以使用的拖拽函数。

使用方法

需要先设置position属性,absolute relative fixed均可

#app{
  position: absolute;
}

传入需要被拖拽元素节点

new Drafting(document.querySelector('#app'))

原理

注意事项

  1. app上监听mousedown 及 mouseup 事件
  2. document上监听mousemove事件
  3. 偏移的值需要用当前的位置减掉起始的位置再加上之前所设置的 left 或 top 的值

以下为详细代码

class Drafting{
  constructor(el){
    this.$el = el
    this.$move = false
    this.$position = []
    this.$type = null

    this.judge()
  }

  judge(){
    if('ontouchstart' in document.body){
      this.$type = 'phone'
      this.listen('touchstart','touchmove','touchend')
    }else{
      this.$type = 'pc'
      this.listen('mousedown','mousemove','mouseup')
    }
  }
  
  listen(x,y,z){
    this.$el.addEventListener(x,(e)=>{
      this.$move = true
      this.$type === 'phone'? this.$position = [e.targetTouches[0].clientX,e.targetTouches[0].clientY] : this.$position = [e.clientX,e.clientY]
    })
    document.addEventListener(y,(e)=>{
      if(!this.$move) return
      let x = null
      let y = null
      this.$type === 'phone'? x = e.targetTouches[0].clientX : x = e.clientX
      this.$type === 'phone'? y = e.targetTouches[0].clientY : y = e.clientY
      let gapX = `${x - this.$position[0] + parseInt(this.$el.style.left || 0)}`
      let gapY = `${y - this.$position[1] + parseInt(this.$el.style.top || 0)}`
      this.$el.style.left = `${gapX}px`
      this.$el.style.top = `${gapY}px`
      this.$position = [x,y]
    })
    this.$el.addEventListener(z,()=>{
      this.$move = false
    })
  }
}

new Drafting(document.querySelector('#app'))
上一篇 下一篇

猜你喜欢

热点阅读