//自定义指令
directives: {
drag: {
// 指令的定义
bind: function(el) {
let oDiv = el; // 获取当前元素
oDiv.onmousedown = (e) => {
// 算出鼠标相对元素的位置
let disX = e.clientX - oDiv.offsetLeft;
let disY = e.clientY - oDiv.offsetTop;
console.log("本身的宽高",oDiv.clientHeight);
document.onmousemove = (e) => {
// 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - disX;
let top = e.clientY - disY;
if (left <= 0) {
left = 0;
} else if (left >= document.documentElement.clientWidth - oDiv.clientWidth){
//document.documentElement.clientWidth 屏幕的可视宽度
left = document.documentElement.clientWidth - oDiv.clientWidth
}
if (top <= 0) {
top = 0;
} else if (top >= document.documentElement.clientHeight - oDiv.clientHeight){
// document.documentElement.clientHeight 屏幕的可视高度
top = document.documentElement.clientHeight - oDiv.clientHeight
}
oDiv.style.left = left + 'px';
oDiv.style.top = top + 'px';
};
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
}
}
}
}
},
<div v-drag ></div>//使用v-drag