vue自定义拖动指令

243 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第3天,点击查看活动详情

代码如下:

drag: function (el) {
  let dragBox = el; //获取当前元素
  dragBox.onmousedown = (e) => {
    //算出鼠标相对元素的位置
    let disX = e.clientX - dragBox.offsetLeft;
    let disY = e.clientY - dragBox.offsetTop;
    document.onmousemove = (e) => {
      //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
      let left = e.clientX - disX;
      let top = e.clientY - disY;
      if (left < 0) left = 0;
      if (top < 0) top = 0;
      //移动当前元素
      dragBox.style.left = left + "px";
      dragBox.style.top = top + "px";
    };
    document.onmouseup = (e) => {
      //鼠标弹起来的时候不再移动
      document.onmousemove = null;
      //预防鼠标弹起来后还会循环(即预防鼠标放上去的时候还会移动)
      document.onmouseup = null;
    };
  };
},

使用的时候

直接在元素上使用v-drag就可以

注意:

盒子要设置相对定位!!