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>
相关推荐
huangyiyi666664 分钟前
Vue + TS 项目文件结构
前端·javascript·vue.js
0思必得022 分钟前
[Web自动化] Selenium处理Cookie
前端·爬虫·python·selenium·自动化
徐同保31 分钟前
react-markdown使用
前端·react.js·前端框架
2601_9498574339 分钟前
Flutter for OpenHarmony Web开发助手App实战:CSS参考
前端·css·flutter
无法长大39 分钟前
如何判断项目需不需要用、能不能用Tailwind CSS
前端·css·vue.js·elementui·vue3·tailwind css
橙露41 分钟前
移动端前端适配:Rem、VW/VH 与媒体查询的综合应用指南
前端·媒体
GGGG寄了1 小时前
CSS——CSS引入方式+选择器类型
前端·css·html
墨染青竹梦悠然1 小时前
基于Django+vue的图书借阅管理系统
前端·vue.js·后端·python·django·毕业设计·毕设
码农六六1 小时前
js函数柯里化
开发语言·前端·javascript