注意:标签拖拽(指令拖拽会有个点击事件,同时有点击事件和拖拽事件的不能使用)
import Vue from 'vue';
// v-domDrag: 标签拖拽(指令拖拽会有个点击事件,同时有点击事件和拖拽事件的不能用)
Vue.directive('domDrag', {
bind(el) {
//el即为当前元素,添加可拖拽标识
el.style.cursor = 'move'
// 获取原有属性 ie dom.currentStyle 火狐谷歌 window.getComputedStyle(dom, null);
const sty = el.currentStyle || window.getComputedStyle(el, null)
el.onmousedown = (e) => {
//获取鼠标按下位置
const disX = e.clientX
const disY = e.clientY
// 获取当前元素的定位信息
// 获取到的值带px 正则匹配替换
let styL, styT
// 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
// +的作用是将字符串转为数字
if (sty.left.includes('%')) {
styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100)
styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
} else {
styL = +sty.left.replace(/\px/g, '')
styT = +sty.top.replace(/\px/g, '')
}
document.onmousemove = function (e) {
// 通过事件委托,计算移动的距离
const l = e.clientX - disX
const t = e.clientY - disY
// 移动当前元素
el.style.left = `${l + styL}px`
el.style.top = `${t + styT}px`
}
//鼠标弹起,移除相应事件
document.onmouseup = function (e) {
document.onmousemove = null
document.onmouseup = null
}
}
}
})<div v-domDrag>拖拽的元素</div>版权声明:本文为sugerinaflat原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。