vue通过自定义事件实现盒子拖拽效果

vue实现盒子拖拽效果(可随意拖动)

思路

1、当盒子被点击时,保存鼠标的位置相对于要移动的盒子的距离(disx、disy)。
2、鼠标移动时,计算要移动的距离。
3、鼠标松开,清除事件。

代码

<div class="father" ref="father">
    <div class="son" v-drag></div>
</div>
 
directives: {
    
    
    drag: (el) => {
    
    
      el.onmousedown = (e) => {
    
    
        //鼠标相对于要移动的盒子的距离
        let disx = e.pageX - el.offsetLeft;
        let disy = e.pageY - el.offsetTop;
        let father = document.querySelector(".father");
        document.onmousemove = function (e) {
    
    
          el.style.cursor = "move";
          let boxL = e.pageX - disx;
          let boxT = e.pageY - disy;
          if (boxL < 0) {
    
    
            //左边锁死
            boxL = 0;
          } else if (boxL + el.offsetWidth >= father.offsetWidth) {
    
    
            //右边锁死
            boxL = father.offsetWidth - el.offsetWidth;
          }
          if (boxT < 0)
            //上边锁死
            boxT = 0;
          else if (boxT + el.offsetHeight >= father.offsetHeight) {
    
    
            boxT = father.offsetHeight - el.offsetHeight;
          }
          el.style.left = boxL + "px";
          el.style.top = boxT + "px";
        };
        document.onmouseup = function () {
    
    
          el.style.cursor = "defalut";
          document.onmousemove = null;
          document.onmouseup = null;
        };
      };
    },
 }

猜你喜欢

转载自blog.csdn.net/m0_53062835/article/details/120102951