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

    // ...
  }
}
相关推荐
开发者小天9 分钟前
React中的 闭包陷阱
前端·javascript·react.js
翔云 OCR API14 分钟前
承兑汇票识别接口技术解析-开发者接口
开发语言·前端·数据库·人工智能·ocr
涔溪22 分钟前
Vue3 的核心语法
前端·vue.js·typescript
G***E3161 小时前
前端在移动端中的React Native Web
前端·react native·react.js
云烟飘渺o1 小时前
JPA 的脏检查:一次“没 save() 却更新了”的排查记录
前端
Neptune11 小时前
深入浅出:理解js的‘万物皆对象’与原型链
前端·javascript
王霸天1 小时前
扒一扒 Vue3 大屏适配插件 vfit 的源码:原来这么简单?
前端
王霸天1 小时前
拒绝 rem 计算!Vue3 大屏适配,我是这样做的 (vfit 使用体验)
前端
xinyu_Jina1 小时前
ikTok Watermark Remover:客户端指纹、行为建模与自动化逆向工程
前端·人工智能·程序人生·信息可视化
Zohnny1 小时前
3.组合式函数
vue.js