vue custom drag and drop

  Vue.directive('drag',//自定义指令
    {
      bind: function (el, binding) {
        let oDiv = el;   //当前元素
        let self = this;  //上下文
        oDiv.onmousedown = function (e) {
          //鼠标按下,计算当前元素距离可视区的距离
          let disX = e.clientX - oDiv.offsetLeft;
          let disY = e.clientY - oDiv.offsetTop;



          document.onmousemove = function (e) {
            //通过事件委托,计算移动的距离
            let l = e.clientX - disX;
            let t = e.clientY - disY;

            var xMax= document.documentElement.clientWidth-100;
            var xMin = 0;
            var yMax = document.documentElement.clientHeight-100;
            var yMin = 50;

            if(l>=xMax){
              l=xMax;
            }else if(l<=xMin){
              l=xMin;
            }

            if(t>=yMax){
              t=yMax;
            }else if(t<=yMin){
              t=yMin;
            }


            //移动当前元素
            oDiv.style.left = l + 'px';
            oDiv.style.top = t + 'px';
            
            //将此时的位置传出去
            binding.value({x: e.pageX, y: e.pageY})
          };
          document.onmouseup = function (e) {

            document.onmousemove = null;
            document.onmouseup = null;
          };
        };
      }
    }
  );

The above is the whole process of custom event, you can also set the draggable area

<div draggable="false" class="content layout-vertical center" v-drag>

      <img draggable="false" src="../../assets/images/calling.png"  style="width: 32px;height: 39px"/>
      <span class="margin-top-10px">正在通话... </span>

  </div>

The above is the usage. Use v-drag to specify the draggable controls. It is worth noting that draggable='false' is also set. This is to turn off the default drag event of the element. For example, the drag event of the image itself will be different from the current drag event. event conflict

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325169964&siteId=291194637