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

    // ...
  }
}
相关推荐
淼淼爱喝水10 分钟前
基于DOM型XSS漏洞与利用实验教程
前端·xss·dom·dvwa
Aotman_41 分钟前
Element UI 表格搜索高亮
前端·javascript·vue.js·ui·elementui
yqcoder1 小时前
[特殊字符] Vue 3 中 Keep-Alive 对生命周期的影响:深度解析
前端·javascript·vue.js
jiayong231 小时前
第 33 课:任务看板视图(按状态分列)与本地持久化
开发语言·前端·javascript·学习
GISer_Jing2 小时前
Dify可视化编排:技术架构与实战指南
前端·人工智能·ai编程
宇宙realman_9992 小时前
DSP28335-FlashAPI使用
linux·前端·python
踩着两条虫2 小时前
VTJ 平台六大设计模式落地实战指南
开发语言·前端·人工智能·低代码·设计模式·重构·架构
Yeats_Liao2 小时前
后台 Sidebar 伸缩交互(PC + 移动端)实现
前端·javascript·css·html5
MXN_小南学前端2 小时前
computed 计算属性详解:触发时机、实战场景、Vue2 与 Vue3 对比
前端·javascript·vue.js
isNotNullX2 小时前
数据大屏怎么做?数据大屏有哪四个核心环节
开发语言·前端·javascript