vue 自定义指令拖拽

2022-12-29 08:06:16
 1、自定义vue指令,位置:和methods、created同级
 directives: {
    drag: {
      // 指令的定义
      bind: function (el) {
        var odiv = el; // 获取当前元素
        var dragFlag = false;
        el.style.position = 'absolute';// 这一步一定不要忘记
        var x, y;
        odiv.style.cursor = "move";
        odiv.onmousedown = (e) => {
          e = e || window.event;
          x = e.clientX - odiv.offsetLeft;
          y = e.clientY - odiv.offsetTop;
          dragFlag = true;
          document.onmousemove = (e) => {
            if (dragFlag) {
              e = e || window.event;
              odiv.style.left = e.clientX - x + "px";
              odiv.style.top = e.clientY - y + "px";
            }
          };
          document.onmouseup = (e) => {
            document.onmousemove = null;
            document.onmouseup = null;
            dragFlag = false;
          };
        };
      },
    },
  },
2、使用
<div style="position: relative">
      <div v-drag style="width: 200px; height: 200px; background: orange">这是一个被拖动的div</div>
 </div>

3、效果

在这里插入图片描述

  • 作者:mxlWhb
  • 原文链接:https://blog.csdn.net/qq_42859450/article/details/122966322
    更新时间:2022-12-29 08:06:16