vue3+ts 指令拖拽div案例
<template>
<div class="box" v-move>
<div class="header"></div>
<div>内容</div>
</div>
</template>
<script setup lang="ts">
import { ref, Directive, DirectiveBinding } from "vue";
const vMove: Directive<any, void> = (el: HTMLElement, bingding: DirectiveBinding) => {
let moveElement: HTMLDivElement = el.firstElementChild as HTMLDivElement;
console.log(moveElement);
const mouseDown = (e: MouseEvent) => {
let X = e.clientX - el.offsetLeft;
let Y = e.clientY - el.offsetTop;
const move = (e: MouseEvent) => {
console.log(e);
el.style.left = e.clientX - X + "px";
el.style.top = e.clientY - Y + "px";
};
document.addEventListener("mousemove", move);
document.addEventListener("mouseup", () => {
document.removeEventListener("mousemove", move);
});
};
moveElement.addEventListener("mousedown", mouseDown);
};
</script>
<style lang="scss">
.box {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
border: 3px solid black;
.header {
height: 20px;
background: black;
}
}
</style>
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_45932157/article/details/134658440