html部分
<template>
<div class="rectContainer">
<div class="rect" v-drag></div>
</div>
</template>
css部分
<style scoped>
.rectContainer {
width: 500px;
height: 500px;
border: 2px solid black;
position: relative;
}
.rect {
width: 200px;
height: 200px;
background: blue;
position: absolute;
}
</style>
js部分
directives: {
drag: {
inserted: function(el, binding) {
el.onmousedown = e => {
var disX = e.clientX - el.offsetLeft;
var disY = e.clientY - el.offsetTop;
document.onmousemove = e => {
var x = e.clientX - disX;
var y = e.clientY - disY;
el.style.left = x + "px";
el.style.top = y + "px";
};
document.onmouseup = () => {
document.onmousemove = null;
};
};
}
}
},