代码很简单 直接看就行
<template>
<div class="draggable"
:style="{ top: dragPosition.top + 'px', left: dragPosition.left + 'px' }"
@mousedown="startDrag"
ref="draggableRef">
拖动我!
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const draggableRef = ref(null);
const dragPosition = ref({ top: 0, left: 0 });
const isDragging = ref(false);
let initialMousePosition = ref({ x: 0, y: 0 });
const startDrag = (event) => {
isDragging.value = true;
initialMousePosition.value = {
x: event.clientX,
y: event.clientY
};
document.addEventListener('mousemove', doDrag);
document.addEventListener('mouseup', endDrag);
};
const doDrag = (event) => {
if (isDragging.value) {
const offset = {
x: event.clientX - initialMousePosition.value.x,
y: event.clientY - initialMousePosition.value.y
};
dragPosition.value = {
top: dragPosition.value.top + offset.y,
left: dragPosition.value.left + offset.x
};
initialMousePosition.value = { x: event.clientX, y: event.clientY };
}
};
const endDrag = () => {
isDragging.value = false;
document.removeEventListener('mousemove', doDrag);
document.removeEventListener('mouseup', endDrag);
};
onMounted(() => {
// 初始化位置,如果需要的话
});
</script>
<style scoped>
.draggable {
position: fixed;
width: 100px;
height: 100px;
background-color: red;
cursor: move;
}
</style>