vue3中怎么实现多个div通过定义一个函数useDraggable实现拖动?

https://play.vuejs.org/#eNqlVE2PmzAQ/StTLkskStIes9nVtmpV9dBL1...

上面地址中的代码需要修改成:
1:鼠标在红或绿色div上按下后移动鼠标,则相应的div会随着鼠标移动。
2:不管是红还是绿色div鼠标按下移动时不能超出窗口的边界。

有人知道怎么修改不?对鼠标那块的知识不怎么熟,学了忘。

阅读 2.7k
1 个回答
<template>
  <div 
    :style="{ left: `${elRed.x}px`, top: `${elRed.y}px`, position: 'fixed', background: 'red' }" 
    @mousedown="elRed.start" 
    @mousemove="elRed.move" 
    @mouseup="elRed.end"
    @mouseleave="elRed.end"
  >
    Drag me! I am at {{ elRed.x }}, {{ elRed.y }}
  </div>
  <br/>
  <div 
    :style="{ left: `${elGreen.x}px`, top: `${elGreen.y}px`, position: 'fixed', background: 'green' }" 
    @mousedown="elGreen.start" 
    @mousemove="elGreen.move" 
    @mouseup="elGreen.end"
    @mouseleave="elGreen.end"
  >
    Drag me! I am at {{ elGreen.x }}, {{ elGreen.y }}
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

function useDraggable() {
  const x = ref(0);
  const y = ref(0);
  const isDragging = ref(false);
  let startX = 0;
  let startY = 0;
  let initialX = 0;
  let initialY = 0;

  const start = (event) => {
    isDragging.value = true;
    startX = event.clientX;
    startY = event.clientY;
    initialX = x.value;
    initialY = y.value;
  };

  const move = (event) => {
    if (isDragging.value) {
      const dx = event.clientX - startX;
      const dy = event.clientY - startY;
      x.value = Math.min(Math.max(initialX + dx, 0), window.innerWidth - 100); // 100 is the width of the div
      y.value = Math.min(Math.max(initialY + dy, 0), window.innerHeight - 100); // 100 is the height of the div
    }
  };

  const end = () => {
    isDragging.value = false;
  };

  return {
    x,
    y,
    isDragging,
    start,
    move,
    end
  };
}

const elRed = useDraggable();
const elGreen = useDraggable();
</script>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏