基于javascript的拖拽类封装详解

2020-06-14 06:24:38易采站长站整理

代码解说

初始化参数

初始化目标dom对象的位置:记录其:

left平距左
top
width
height
angle
rightBottomPoint 目标dom对象右下坐标
rightTopPoint 目标dom对象右上坐标
leftTopPoint 目标dom对象左上坐标
leftBottomPoint 目标dom对象左下坐标
leftMiddlePoint 目标dom对象左中坐标
rightMiddlePoint 目标dom对象右中坐标
topMiddlePoint 目标dom对象上中坐标
bottomMiddlePoint 目标dom对象下中坐标
centerPos 目标dom对象中心点坐标

初始化pannel结构

当前的父容器中只有一个pannel结构,每次实例化对象时,会判断一下如果当前这个父容器里已经存在id为pannel的结构,就将其子节点清空,按照当前实例化对象传进来的属性重新渲染pannel子结构。如果没有id为pannel的结构,就创建。

初始化事件

给pannelDom和targetObj绑定mousedown事件
给document绑定mousemove和mouseup事件

 


initEvent () {
document.addEventListener('mousemove', e => {
e.preventDefault && e.preventDefault()
this.moveChange(e, this.targetObj)
})
document.addEventListener('mouseup', e => {
this.moveLeave(this.targetObj)
})
if (this.canMove) {
// 外层给this.pannelDom添加mousedown事件,是在所有实例化结束后,panneldom被展示在最后一个实例化对象上,鼠标按下它时,触发moveInit事件
this.pannelDom.onmousedown = e => {
e.stopPropagation()
this.moveInit(9, e, this.targetObj)
}
this.targetObj.onmousedown = e => {
e.stopPropagation()
this.moveInit(9, e, this.targetObj)
this.initPannel()
// 在点击其他未被选中元素时,pannel定位到该元素上,重写pannelDom事件,因为此时的this.pannelDom已经根据新的目标元素被重写
this.pannelDom.onmousedown= e => {
this.moveInit(9, e, this.targetObj)
}
}
}
}

dom操作

旋转操作

鼠标按下时,记录当前鼠标位置距离box中心位置的y/x的反正切函数A1。 


this.mouseInit = {
x: Math.floor(e.clientX),
y: Math.floor(e.clientY)
}
this.preRadian = Math.atan2(this.mouseInit.y - this.centerPos.y, this.mouseInit.x - this.centerPos.x)

鼠标移动时,记录再次计算鼠标位置距离box中心位置的y/x的反正切函数A2。


this.rotateCurrent = {
x: Math.floor(e.clientX),
y: Math.floor(e.clientY)
}
this.curRadian = Math.atan2(this.rotateCurrent.y - this.centerPos.y, this.rotateCurrent.x - this.centerPos.x)