Vue realizes box dragging effect through custom events

Vue realizes box dragging effect (can be dragged at will)

train of thought

1. When the box is clicked, save the distance (disx, disy) of the mouse position relative to the box to be moved.
2. When the mouse moves, calculate the distance to move.
3. Release the mouse to clear the event.

the code

<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;
        };
      };
    },
 }

Guess you like

Origin blog.csdn.net/m0_53062835/article/details/120102951