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>
相关推荐
子醉2 小时前
推荐一种适合前端开发使用的解决本地跨域问题的办法
前端
Niyy_2 小时前
前端一个工程构建多个项目,记录一次工程搭建
前端·javascript
xiangxiongfly9152 小时前
CSS link标签
前端·css
快乐非自愿3 小时前
常用设计模式:工厂方法模式
javascript·设计模式·工厂方法模式
岁月宁静3 小时前
AI 多模态全栈应用项目描述
前端·vue.js·node.js
十年磨一剑~3 小时前
html+js开发一个测试工具
javascript·css·html
nn_(nana)4 小时前
修改文件权限--- chmod ,vi/vim,查看文件内容,yum-软件包管理器,systemctl管理系统服务
前端
汪汪队立大功1234 小时前
JavaScript是怎么和html元素关联起来的?
开发语言·javascript·html
烛阴5 小时前
从零开始掌握C#核心:变量与数据类型
前端·c#