Vue 3 + TypeScript + Vite 项目中,实现选中图片移动

复制代码
<template>
  <div class="image-container" @mousedown="startDrag" @mousemove="drag" @mouseup="endDrag">
    <img src="path/to/image.jpg" alt="My Image" ref="imageRef">
  </div>
</template>

在组件的 <script> 标签中,定义相关的数据和方法。首先,使用 Vue 的 ref 函数创建一个对图片元素的引用:

复制代码
<script>
import { ref } from 'vue';

export default {
  setup() {
    const imageRef = ref(null);

    // ...

    return {
      imageRef,
      // ...
    };
  },
};
</script>

接下来,实现选中时出现边框的效果。你可以通过设置 CSS 样式来实现这一点。以下是一个简单的示例:

复制代码
.image-container {
  position: relative;
}

.image-container.selected {
  outline: 2px solid blue;
}

.image-container.selected::before {
  content: '';
  position: absolute;
  top: -5px;
  left: -5px;
  right: -5px;
  bottom: -5px;
  border: 1px dashed blue;
}

在组件的 <template> 中,为选中的容器元素动态绑定 selected 类名。可以通过监听鼠标事件来实现这一点。例如,在 startDrag 方法中添加以下代码:

复制代码
function startDrag() {
  // 添加选中样式
  imageRef.value.parentElement.classList.add('selected');

  // ...
}

endDrag 方法中移除选中样式:

复制代码
function endDrag() {
  // 移除选中样式
  imageRef.value.parentElement.classList.remove('selected');

  // ...
}

实现拖动图片的功能。在 drag 方法中,计算鼠标移动的距离,并将其应用于图片元素的位置。这里可以使用鼠标事件的 clientXclientY 属性来获取鼠标的位置。以下是一个简单的示例:

复制代码
function drag(event) {
  // 确保只有当图片被选中时才会触发拖动操作
  if (imageRef.value.parentElement.classList.contains('selected')) {
    const imageElement = imageRef.value;
    const containerElement = imageElement.parentElement;

    const deltaX = event.clientX - containerElement.offsetLeft;
    const deltaY = event.clientY - containerElement.offsetTop;

    imageElement.style.left = `${deltaX}px`;
    imageElement.style.top = `${deltaY}px`;

    // ...
  }
}
相关推荐
神算大模型APi--天枢6465 分钟前
合规与高效兼得:国产全栈架构赋能行业大模型定制,从教育到工业的轻量化落地
大数据·前端·人工智能·架构·硬件架构
千寻girling10 分钟前
马上元旦节了,手写一个《前端脚手架》庆祝一下 !
前端
嚣张丶小麦兜27 分钟前
认识vite
前端·javascript·vue.js
玲小珑1 小时前
请求 ID 跟踪模式:解决异步请求竞态条件
前端
开心_开心急了1 小时前
AI+PySide6实现自定义窗口标题栏目(titleBar)
前端
开心_开心急了1 小时前
Ai加Flutter实现自定义标题栏(appBar)
前端·flutter
布列瑟农的星空1 小时前
SSE与流式传输(Streamable HTTP)
前端·后端
GISer_Jing2 小时前
跨境营销前端AI应用业务领域
前端·人工智能·aigc
oak隔壁找我2 小时前
Node.js的package.json
前端·javascript
talenteddriver2 小时前
web: http请求(自用总结)
前端·网络协议·http