代码如下:
directives: {
drag: function (el) {
let dragBox = el; //获取当前元素
dragBox.onmousedown = (e) => {
//算出鼠标相对元素的位置
let disX = e.clientX - dragBox.offsetLeft;
let disY = e.clientY - dragBox.offsetTop;
document.onmousemove = (e) => {
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - disX;
let top = e.clientY - disY;
if (left < 0) left = 0;
if (top < 0) top = 0;
//移动当前元素
dragBox.style.left = left + "px";
dragBox.style.top = top + "px";
};
document.onmouseup = (e) => {
//鼠标弹起来的时候不再移动
document.onmousemove = null;
//预防鼠标弹起来后还会循环(即预防鼠标放上去的时候还会移动)
document.onmouseup = null;
};
};
},
},
使用的时候
直接在元素上使用v-drag就可以
<div v-drag class="poa box t-20 r-20 w-198 h-224">
<el-card :body-style="{ padding: '10px' }">
<div slot="header" class="bg-gray pl-20 text-black">图例</div>
<p-table />
</el-card>
</div>
注意:
盒子要设置相对定位!!