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>
相关推荐
daols883 小时前
vue vxe-table 自适应列宽,根据内容自适应宽度的2种使用方式
vue.js·vxe-table
小小小小宇4 小时前
虚拟列表兼容老DOM操作
前端
悦悦子a啊4 小时前
Python之--基本知识
开发语言·前端·python
安全系统学习5 小时前
系统安全之大模型案例分析
前端·安全·web安全·网络安全·xss
涛哥码咖5 小时前
chrome安装AXURE插件后无效
前端·chrome·axure
OEC小胖胖5 小时前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
行云&流水6 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
Sally璐璐6 小时前
零基础学HTML和CSS:网页设计入门
前端·css
老虎06276 小时前
JavaWeb(苍穹外卖)--学习笔记04(前端:HTML,CSS,JavaScript)
前端·javascript·css·笔记·学习·html
三水气象台6 小时前
用户中心Vue3网页开发(1.0版)
javascript·css·vue.js·typescript·前端框架·html·anti-design-vue