export default class MoveService { constructor(DOM) { if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) { this.DviceType = true } else { this.DviceType = false } this.movedom = null this.w = document.body.clientWidth this.h = document.body.clientHeight this.PX = 0 this.PY = 0 this.domw = 0 this.domh = 0 this.on(DOM) } /** * 移动 */ mousemove(event) { const e = event || window.event const x = this.DviceType ? e.touches[0].clientX : e.clientX const y = this.DviceType ? e.touches[0].clientY : e.clientY const mx = x - this.PX const my = y - this.PY const outx = this.w - this.domw const outy = this.h - this.domh this.movedom.style.left = `${mx}px` this.movedom.style.top = `${my}px` if (mx >= outx) { this.movedom.style.left = `${outx}px` } if (my >= outy) { this.movedom.style.top = `${outy}px` } if (mx <= 0) { this.movedom.style.left = '0px' } if (my <= 0) { this.movedom.style.top = '0px' } } /** * 鼠标按下 */ mousedown(event) { // 获取点击DOM const e = event || window.event if (this.DviceType) { this.PX = e.touches[0].clientX - this.movedom.offsetLeft this.PY = e.touches[0].clientY - this.movedom.offsetTop this.movedom.ontouchmove = this.mousemove.bind(this) this.movedom.ontouchend = this.mouseup.bind(this) } else { this.PX = e.clientX - this.movedom.offsetLeft this.PY = e.clientY - this.movedom.offsetTop this.movedom.onmousemove = this.mousemove.bind(this) this.movedom.onmouseup = this.mouseup.bind(this) } } /** * 鼠标松开 */ mouseup() { this.off() } /** * 监听鼠标 * @param dom dom元素 */ on(dom) { this.movedom = dom try { if (this.DviceType) { this.movedom.ontouchstart = this.mousedown.bind(this) } else { this.movedom.onmousedown = this.mousedown.bind(this) } this.domw = parseInt(window.getComputedStyle(this.movedom).width) this.domh = parseInt(window.getComputedStyle(this.movedom).height) } catch (error) { console.warn('dom 获取失败') } } /** * 移除监听 */ off() { this.movedom.onmousemove = null this.movedom.onmouseup = null this.movedom.ontouchmove = null this.movedom.ontouchend = null } }