vue3 简单的元素拖动

代码很简单 直接看就行

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值