【VUE】Vue3自由拖拽标签

效果:

代码:

html 复制代码
<template>
<div>
    <div v-move class="box">
    <label class="move">拽我</label>  
    </div>
</div>
</template>
<script setup lang="ts">
    import { ref, Directive  } from 'vue';
    const vMove: Directive = {
    mounted(el: HTMLElement) {
        let moveEl = el.firstElementChild as HTMLElement;
        const mouseDown = (e: MouseEvent) => {
        //鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
        console.log(e.clientX, e.clientY, "-----起始", el.offsetLeft);
        let X = e.clientX - el.offsetLeft;
        let Y = e.clientY - el.offsetTop;
        const move = (e: MouseEvent) => {
            el.style.position = 'absolute';
            el.style.left = e.clientX - X + "px";
            el.style.top = e.clientY - Y + "px";
            console.log(e.clientX, e.clientY, "---改变");
        };
        document.addEventListener("mousemove", move);
        document.addEventListener("mouseup", () => {
            document.removeEventListener("mousemove", move);
        });
        };
        moveEl.addEventListener("mousedown", mouseDown);
    },
    }; 
</script>
<style lang="scss" scoped>
label{
    text-align: center;
    display: block;
    height: 30px;
    line-height: 30px;
    border: 1px solid #000;
    cursor:move;
}
.box {
  position: relative;
  left: 150px;
  top: 70px;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 0;
  .move {
    text-align: center;
    display: block;
    height: 30px;
    line-height: 30px;
    border: 1px solid #000;
    cursor:move;
  }
}
</style>

ps:写完之后就忘了是参考的哪一个地址,如果雷同或侵犯到请告知,我会及时删除该博文。

相关推荐
喝拿铁写前端12 分钟前
前端 Emoji 注释规范实践:VSCode 插件 Emoji 注释增强器分享
前端·开源·代码规范
石小石Orz1 小时前
如何将本地文件转成流数据传递给后端?
前端·vue.js
德育处主任Pro2 小时前
AntV L7入门教程
前端框架
RPGMZ2 小时前
RPGMZ游戏引擎之如何设计每小时开启一次的副本
javascript·游戏·游戏引擎·rpgmz
RPGMZ2 小时前
RPGMZ游戏引擎 如何手动控制文字显示速度
开发语言·javascript·游戏引擎·rpgmz
Codebee2 小时前
OneCode核心概念解析——View(视图)
前端·人工智能
GIS之路2 小时前
GIS 数据质检:验证 Geometry 有效性
前端
GIS之路2 小时前
GeoJSON 数据简介
前端
今阳2 小时前
鸿蒙开发笔记-16-应用间跳转
android·前端·harmonyos
前端小饭桌2 小时前
CSS属性值太多记不住?一招教你搞定
前端·css