一个在移动端及PC端都可以使用的拖拽函数。
使用方法
需要先设置position属性,absolute relative fixed均可
#app{
position: absolute;
}
传入需要被拖拽元素节点
new Drafting(document.querySelector('#app'))
原理
- 假设在PC端上
- 监听app的mousedown事件,取得此时的位置[x1,y1]
- 监听mousemove事件,取得此时的位置[x2,y2]
- 则两个位置之间的差值就为app需要设置的left及top值
注意事项
- app上监听mousedown 及 mouseup 事件
- document上监听mousemove事件
- 偏移的值需要用当前的位置减掉起始的位置再加上之前所设置的 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'))