javascript
<template>
<div v-move class="box">
</div>
</template>
<script setup lang="ts">
import { Directive } from 'vue'
const vMove:Directive = (el:HTMLElement) =>{
const mousedown = (e:MouseEvent) =>{
// 鼠标按下
const startX = e.clientX - el.offsetLeft;
const startY = e.clientY - el.offsetHeight;
const move = (e:MouseEvent)=> {
console.log('坐标',e.clientX, e.clientY);
// 鼠标移动
const moveX = e.clientX;
const moveY = e.clientY;
const disX = moveX - startX;
const disY = moveY - startY;
el.style.top = disY + 'px'
el.style.left = disX + 'px'
}
const up = () => {
// 鼠标抬起
document.removeEventListener('mousemove',move)
document.removeEventListener('mouseup',up)
}
document.addEventListener('mousemove',move)
document.addEventListener('mouseup',up)
}
el.addEventListener('mousedown',mousedown)
}
</script>
<style scoped>
.box {
width: 400px;
height: 400px;
background: pink;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>