vue前端元素任意拖拽效果-解决拖拽有时失效问题、不能快速拖拽问题、根据父元素设置可拖拽元素的范围问题

vue - main.js文件

// 在vue  main.js文件中加上这个,然后就可以使用vue的快捷指令
Vue.directive("drag", {
  inserted: function(el){
      let odiv = el;   //获取当前元素
      odiv.onmousedown = (e) => {
          //算出鼠标相对元素的位置
          let disX = e.clientX - odiv.offsetLeft;
          let disY = e.clientY - odiv.offsetTop;
          // 为什么用document:如果绑定到元素本身的情况下,鼠标拖动过快,鼠标会离开拖拽的元素,导致拖拽一段距离,拖拽失效的问题
          document.onmousemove = (e)=>{
              //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
              let left = e.clientX - disX;
              let top = e.clientY - disY;
              //绑定元素位置到positionX和positionY上面
              // this.positionX = top;
              // this.positionY = left;
              let FWidth = el.parentNode.offsetWidth - el.offsetWidth;
              let FHeight = el.parentNode.offsetHeight - el.offsetHeight;
              //移动当前元素
              // console.log('left' + left);
              // console.log('top' + top);
              // 判断当前元素可以活动的区域
              if (left <= 0) {
                odiv.style.left = 0 + 'px';
              } else if (left >= FWidth) {
                odiv.style.left = FWidth + 'px';
              } else if (left > 0) {
                odiv.style.left = left + 'px';
              }
              if (top <= 0) {
                odiv.style.top = 0 + 'px';
              } else if (top >= FHeight) {
                odiv.style.top = FHeight + 'px';
              }  else if (top > 0) {
                odiv.style.top = top + 'px';
              }
          };
          document.onmouseup = (e) => {
              document.onmousemove = null;
              document.onmouseup = null;
          };
      };
  }
});

vue文件使用:



你可能感兴趣的:(vue前端元素任意拖拽效果-解决拖拽有时失效问题、不能快速拖拽问题、根据父元素设置可拖拽元素的范围问题)