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从业者6 小时前
Python + 淘宝 API 开发:自动化采集商品数据的完整流程
大数据·运维·前端·数据挖掘·自动化
烛阴7 小时前
TypeScript高手密技:解密类型断言、非空断言与 `const` 断言
前端·javascript·typescript
样子20188 小时前
Uniapp 之renderjs解决swiper+多个video卡顿问题
前端·javascript·css·uni-app·html
Nicholas688 小时前
flutterAppBar之SystemUiOverlayStyle源码解析(一)
前端
黑客飓风8 小时前
JavaScript 性能优化实战大纲
前端·javascript·性能优化
emojiwoo10 小时前
【前端基础知识系列六】React 项目基本框架及常见文件夹作用总结(图文版)
前端·react.js·前端框架
张人玉10 小时前
XML 序列化与操作详解笔记
xml·前端·笔记
杨荧10 小时前
基于Python的宠物服务管理系统 Python+Django+Vue.js
大数据·前端·vue.js·爬虫·python·信息可视化
YeeWang11 小时前
🎉 Eficy 让你的 Cherry Studio 直接生成可预览的 React 页面
前端·javascript
gnip11 小时前
Jenkins部署前端项目实战方案
前端·javascript·架构