效果:
代码:
<template>
<div>
<div v-move class="box">
<label class="move">拽我</label>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, Directive } from 'vue';
const vMove: Directive = {
mounted(el: HTMLElement) {
let moveEl = el.firstElementChild as HTMLElement;
const mouseDown = (e: MouseEvent) => {
//鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
console.log(e.clientX, e.clientY, "-----起始", el.offsetLeft);
let X = e.clientX - el.offsetLeft;
let Y = e.clientY - el.offsetTop;
const move = (e: MouseEvent) => {
el.style.position = 'absolute';
el.style.left = e.clientX - X + "px";
el.style.top = e.clientY - Y + "px";
console.log(e.clientX, e.clientY, "---改变");
};
document.addEventListener("mousemove", move);
document.addEventListener("mouseup", () => {
document.removeEventListener("mousemove", move);
});
};
moveEl.addEventListener("mousedown", mouseDown);
},
};
</script>
<style lang="scss" scoped>
label{
text-align: center;
display: block;
height: 30px;
line-height: 30px;
border: 1px solid #000;
cursor:move;
}
.box {
position: relative;
left: 150px;
top: 70px;
transform: translate(-50%, -50%);
width: 200px;
height: 0;
.move {
text-align: center;
display: block;
height: 30px;
line-height: 30px;
border: 1px solid #000;
cursor:move;
}
}
</style>