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

    // ...
  }
}
相关推荐
北凉温华11 分钟前
Vue 3 + AntV X6 实现流程编辑功能
前端·vue.js
栀一一20 分钟前
Typescript缩小类型范围
typescript
独立开阀者_FwtCoder26 分钟前
从卡顿到丝滑,AI 应用体验跃升的幕后推手是它!
前端·vue.js·面试
知否技术30 分钟前
2025微信小程序开发实战教程(二)
前端·微信小程序
前端小巷子33 分钟前
跨标签页通信(一):BroadcastChannel
前端·面试·浏览器
前端付豪33 分钟前
微信支付风控系统揭秘:交易评分、实时拦截与行为建模全流程实战
前端·后端·架构
我有CV两法可开前端一片天35 分钟前
uni-app实现文件上传、下载、预览(非只图片和视频)
前端
断竿散人38 分钟前
CSS布局完全指南(下)-Flexbox完全征服指南:一维布局的终极解决方案
前端·css
前端付豪39 分钟前
微信视频号推荐系统揭秘:兴趣建模、多模态分析与亿级流控架构实战
前端·后端·算法
Aisanyi39 分钟前
【鸿蒙开发】PC实现开局沉浸式全屏
前端·华为·harmonyos