1、自定义vue指令,位置:和methods、created同级
directives: {
drag: {
// 指令的定义
bind: function (el) {
var odiv = el; // 获取当前元素
var dragFlag = false;
el.style.position = 'absolute';// 这一步一定不要忘记
var x, y;
odiv.style.cursor = "move";
odiv.onmousedown = (e) => {
e = e || window.event;
x = e.clientX - odiv.offsetLeft;
y = e.clientY - odiv.offsetTop;
dragFlag = true;
document.onmousemove = (e) => {
if (dragFlag) {
e = e || window.event;
odiv.style.left = e.clientX - x + "px";
odiv.style.top = e.clientY - y + "px";
}
};
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
dragFlag = false;
};
};
},
},
},
2、使用
<div style="position: relative">
<div v-drag style="width: 200px; height: 200px; background: orange">这是一个被拖动的div</div>
</div>
3、效果