vue,div实现拖动,并给新位置

鼠标方上去随意拖动到其它位置

复制代码
<template>
  <div style="margin: 50px;">
    <div class="dade draggable-div"  @mousedown="startDrag($event)" @mouseup="stopDrag" @mousemove="drag($event)"
    style="width: 200px;height: 200px;border: 1px solid #e7e7e7;cursor: all-scroll;">
    </div>
  </div>
</template>

<script>


export default {
  data() {
    return {
      isDragging: false,
      startX: 0,
      startY: 0,
      currentX: 0,
      currentY: 0
    };
  },
  watch: {

  },
  //界面没出来前加载
  created() {
    this.list = menu_tree;
  },
  mounted() {

  },
  computed: {

  },
  methods: {
    //鼠标按下
    startDrag(event) {
      this.isDragging = true;
      this.startX = event.clientX;
      this.startY = event.clientY;
      this.currentX = parseInt(event.target.offsetLeft);
      this.currentY = parseInt(event.target.offsetTop);
      // event.target.style.cursor = 'grabbing';
      document.addEventListener('mousemove', this.drag);
      document.addEventListener('mouseup', this.stopDrag);
    },
    drag(event) {
      if (this.isDragging) {
        const diffX = event.clientX - this.startX;
        const diffY = event.clientY - this.startY;
        event.target.style.left = this.currentX + diffX + 'px';
        event.target.style.top = this.currentY + diffY + 'px';
      }
    },
    stopDrag() {
      this.isDragging = false;
      // event.target.style.cursor = 'grab';
      document.removeEventListener('mousemove', this.drag);
      document.removeEventListener('mouseup', this.stopDrag);
    }
  }
};
</script>

<style scoped>
  .dade{
    -webkit-box-shadow: 0 2px 0px 0 rgba(0,0,0,.1);
     box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }
  .draggable-div {
    position: absolute;
  }
</style>
相关推荐
0思必得04 分钟前
[Web自动化] Selenium模拟用户的常见操作
前端·python·selenium·自动化
十六年开源服务商8 分钟前
WordPress在线聊天系统推荐
大数据·javascript·html
Apifox.16 分钟前
测试用例越堆越多?用 Apifox 测试套件让自动化回归更易维护
运维·前端·后端·测试工具·单元测试·自动化·测试用例
玉梅小洋31 分钟前
Chrome设置链接自动跳转新标签页而不是覆盖
前端·chrome
EndingCoder37 分钟前
反射和元数据:高级装饰器用法
linux·运维·前端·ubuntu·typescript
Marshmallowc41 分钟前
React性能优化:useState初始值为什么要用箭头函数?深度解析Lazy Initialization与Fiber机制
前端·react.js·性能优化·前端框架·react hooks
喵喵喵小鱼41 分钟前
arcgis JavaScript api实现同时展示多个撒点气泡
开发语言·javascript·arcgis
Coder_Boy_44 分钟前
基于SpringAI的在线考试系统-试卷管理模块完整优化方案
前端·人工智能·spring boot·架构·领域驱动
摇滚侠1 小时前
Node.js 零基础教程,Node.js 和 NPM 的安装与使用
前端·npm·node.js
谢尔登1 小时前
Vue3架构设计——调度系统
前端·javascript·vue.js