【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:写完之后就忘了是参考的哪一个地址,如果雷同或侵犯到请告知,我会及时删除该博文。

相关推荐
LFly_ice27 分钟前
学习React-10-useTransition
前端·学习·react.js
咔咔一顿操作29 分钟前
【CSS 3D 交互】实现精美翻牌效果:从原理到实战
前端·css·3d·交互·css3
知识分享小能手33 分钟前
React学习教程,从入门到精通,React 构造函数(Constructor)完整语法知识点与案例详解(16)
前端·javascript·学习·react.js·架构·前端框架·vue
召摇38 分钟前
Nue.js深度解析:极简主义前端框架的革新实践
前端·node.js
小徐_233341 分钟前
uni-app 也能使用 App.vue?wot-starter 是这样实现的!
前端·uni-app
入秋42 分钟前
Three.js后期处理实战:镜头颜色、色差、点阵与颜色管道的深度解析
前端·three.js
深圳外环高速43 分钟前
企业微信和页面离开事件
前端
召摇1 小时前
NodeBB 深度解析:现代论坛系统的架构设计与实践指南
前端·javascript
Abadbeginning1 小时前
FastSoyAdmin centos7云服务器+宝塔部署
vue.js·后端·python
哆啦A梦15881 小时前
uniapp分包实现
前端·vue.js·uni-app·vue3