先给需要拖拽的div盒子标签加上v-drag
<div class="box_mid" v-drag> </div>
<script>
export default {
data() {
return {
};
},
directives: {
drag: {
// 指令的定义
bind: function(el) {
let oDiv = el; // 获取当前元素
oDiv.onmousedown = e => {
// 算出鼠标相对元素的位置
let disX = e.clientX - oDiv.offsetLeft;
let disY = e.clientY - oDiv.offsetTop;
document.onmousemove = e => {
// 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - disX;
let top = e.clientY - disY;
oDiv.style.left = left + 'px';
oDiv.style.top = top + 'px';
};
document.onmouseup = e => {
document.onmousemove = null;
document.onmouseup = null;
};
};
}
}
},
</script>
拖拽实则就是改变left和top的距离,
所以在需要拖拽的盒子样式需要加上 position: relative;否则无法改变left和top的值实现拖拽。