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>
相关推荐
lsp程序员0102 小时前
使用 Web Workers 提升前端性能:让 JavaScript 不再阻塞 UI
java·前端·javascript·ui
J***Q2923 小时前
前端路由,React Router
前端·react.js·前端框架
1***81533 小时前
前端路由参数传递,React与Vue实现
前端·vue.js·react.js
q***13613 小时前
十七:Spring Boot依赖 (2)-- spring-boot-starter-web 依赖详解
前端·spring boot·后端
xixixi777774 小时前
了解一下Sentry(一个开源的实时错误监控平台)
前端·安全·开源·安全威胁分析·监控·sentry
Keely402855 小时前
学习编写chrome插件:Hello World 扩展
前端·chrome
hhcccchh5 小时前
学习vue第三天 Vue 前端项目结构的说明
前端·vue.js·学习
卷福同学6 小时前
【AI编程】用Codebuddy+lighthouse开发AI年龄模拟网站
javascript·后端
源力祁老师6 小时前
Odoo 19 制造与会计集成深度解析
前端·javascript·制造