vue自定义v-drag拖拽指令

HTML:

<div class="crop-modal" v-drag draggable="false">
    可拖动的地方
</div>

在directives中自定义指令 v-drag
directives与data平级

directives: {
    drag (el) {
      let oDiv = el // 当前元素
      // let self = this // 上下文
      // 禁止选择网页上的文字
      document.onselectstart = function () {
        return false
      }
      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
          // 移动当前元素
          oDiv.style.left = l + 'px'
          oDiv.style.top = t + 'px'
        }
        document.onmouseup = function (e) {
          document.onmousemove = null
          document.onmouseup = null
        }
        // return false不加的话可能导致黏连,就是拖到一个地方时div粘在鼠标上不下来,相当于onmouseup失效
        return false
      }
    }
  },

CSS:

.crop-modal{
	position: fixed;
    left: 0;
    top: 0;
    z-index: 99;
}

版权声明:本文为weixin_54666101原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。