面向对象拖拽实现

// 拖拽实现

// 属性 包含拖拽盒子的大盒子 拖拽的盒子 盒子的坐标位置

class Touch {

constructor(outerBox, move) {

this.outerBox = outerBox //包含的盒子

this.move = move //移动的盒子

this.point = { //坐标位置

x: parseInt(this.getStyle(move).left) || 0,

y: parseInt(this.getStyle(move).top) || 0

} //基础坐标为0,0

this.handlerDown()

}

//获取样式的方法

getStyle(element) {

return window.getComputedStyle ? window.getComputedStyle(element, '') :

element.currentStyle

}

//按下

handlerDown(){

this.move.onmousedown = (e)=>{

e = e || window.event

//获取第一次按下的位置

let currentX = e.offsetX

let currentY = e.offsetY

//调用移动的方法

this.handlerMove(currentX,currentY)

//调用弹起的方法

this.handlerUp()

}

}

//弹起

handlerUp(){

document.onmouseup = ()=>{

this.outerBox.onmousemove = null

}

}

//移动

handlerMove(currentX,currentY){

//给大盒子添加移动事件

this.outerBox.onmousemove = (e) => {

e = e || window.event

//大盒子在页面上的位置

let { x, y } = this.getPagePoint(this.outerBox)

//获取移动的位置 - 大盒子在页面上的位置 - 当前按下位置

let { targetX, targetY } = {

targetX: e.pageX - x - currentX,

targetY: e.pageY - y - currentY

}

let { maxX, maxY } = {基于面向的拖拽实现放大镜

maxX: this.outerBox.offsetWidth - this.move.offsetWidth,

maxY: this.outerBox.offsetHeight - this.move.offsetHeight

}

//区间判断

if (targetX < 0) {

targetX = 0

}

if (targetX > maxX) {

targetX = maxX

}

if (targetY < 0) {

targetY = 0

}

if (targetY > maxY) {

targetY = maxY

}

//将对应的位置设置进去

this.point = { x: targetX, y: targetY }

this.setMovePoint()

}

}

setMovePoint() {

//设置

this.move.style.left = this.point.x + 'px'

this.move.style.top = this.point.y + 'px'

}

getPagePoint(element) {

let x = 0

let y = 0

while (element.offsetParent) {

x += element.offsetLeft

y += element.offsetTop

element = element.offsetParent

}

return { x, y }

}

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容