| | |
| | | const drag = { |
| | | mounted(el, binding) { |
| | | mounted(el, binding) { |
| | | const dragBox = document.querySelector('#' + binding.arg) |
| | | //鼠标点击距离box盒子left的距离 |
| | | let spotToBoxLeft = 0 |
| | | let spotToBoxTop = 0 |
| | | |
| | | const dragBox = document.querySelector('#' + binding.arg) |
| | | //鼠标点击距离box盒子left的距离 |
| | | let spotToBoxLeft = 0 |
| | | let spotToBoxTop = 0 |
| | | const mouseupFun = e => { |
| | | window.removeEventListener('mousemove', mousemoveFun) |
| | | window.removeEventListener('mouseup', mouseupFun) |
| | | } |
| | | |
| | | const mouseupFun = (e) => { |
| | | window.removeEventListener('mousemove', mousemoveFun) |
| | | window.removeEventListener('mouseup', mouseupFun) |
| | | } |
| | | const mousemoveFun = evt => { |
| | | console.log(66666) |
| | | //获取body宽高,获取拖动盒子的宽高 |
| | | const { offsetWidth: bodyWidth, offsetHeight: bodyHeight } = document.body |
| | | const { offsetWidth: boxWidth, offsetHeight: boxHeight } = dragBox |
| | | //max取最大值,min取最小值 |
| | | const left = Math.max(evt.clientX - spotToBoxLeft, 0) |
| | | const top = Math.max(evt.clientY - spotToBoxTop, 0) |
| | | dragBox.style.left = Math.min(left, bodyWidth - boxWidth) + 'px' |
| | | dragBox.style.top = Math.min(top, bodyHeight - boxHeight) + 'px' |
| | | } |
| | | |
| | | const mousemoveFun = (evt) => { |
| | | console.log(66666); |
| | | //获取body宽高,获取拖动盒子的宽高 |
| | | const {offsetWidth: bodyWidth, offsetHeight: bodyHeight} = document.body |
| | | const {offsetWidth: boxWidth, offsetHeight: boxHeight} = dragBox |
| | | //max取最大值,min取最小值 |
| | | const left = Math.max(evt.clientX - spotToBoxLeft, 0) |
| | | const top = Math.max(evt.clientY - spotToBoxTop, 0) |
| | | dragBox.style.left = Math.min(left, bodyWidth - boxWidth) + 'px' |
| | | dragBox.style.top = Math.min(top, bodyHeight - boxHeight) + 'px' |
| | | } |
| | | el.__mousedownFun = evt => { |
| | | //鼠标坐标减去 box盒子相对于父盒子body 的距离 |
| | | spotToBoxLeft = evt.clientX - dragBox.offsetLeft |
| | | spotToBoxTop = evt.clientY - dragBox.offsetTop |
| | | window.addEventListener('mousemove', mousemoveFun) |
| | | window.addEventListener('mouseup', mouseupFun) |
| | | } |
| | | el.addEventListener('mousedown', el.__mousedownFun) |
| | | }, |
| | | |
| | | el.__mousedownFun = (evt) => { |
| | | //鼠标坐标减去 box盒子相对于父盒子body 的距离 |
| | | spotToBoxLeft = evt.clientX - dragBox.offsetLeft |
| | | spotToBoxTop = evt.clientY - dragBox.offsetTop |
| | | window.addEventListener('mousemove', mousemoveFun) |
| | | window.addEventListener('mouseup', mouseupFun) |
| | | } |
| | | el.addEventListener('mousedown', el.__mousedownFun); |
| | | }, |
| | | |
| | | // 绑定元素的父组件卸载前调用 |
| | | beforeUnmount(el, binding,) { |
| | | el.removeEventListener('mousedown', el.__mousedownFun) |
| | | }, |
| | | // 绑定元素的父组件卸载前调用 |
| | | beforeUnmount(el, binding) { |
| | | el.removeEventListener('mousedown', el.__mousedownFun) |
| | | }, |
| | | } |
| | | |
| | | export default drag |