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>
相关推荐
SsunmdayKT6 分钟前
前后端项目部署与运行机制全流程详解
前端·后端
本末倒置1837 分钟前
Vue 3 开发者转型 React 指南:保姆级教程
前端·javascript·vue.js
Reart9 分钟前
从0解构tinyWeb项目--(Day:10)
前端·后端·架构
牛蛙点点申请出战1 小时前
IconFontViewer -- 一个可以在 Android Studio 中实时预览 IconFont 的插件
android·前端·intellij idea
空中海1 小时前
03 渲染机制、性能优化与现代 React
javascript·react.js·性能优化
ChalesXavier2 小时前
Fetch API 的基本用法
javascript
是上好佳佳佳呀2 小时前
【前端(十三)】JavaScript 数组与字符串笔记
前端·javascript·笔记
巴沟旮旯儿2 小时前
vite项目配置文件和打包
前端·设计模式
彩票管理中心秘书长2 小时前
Pinia 插件架构与组合式函数:如何让你的 Store 长出“超能力”
前端