vue instruction implements window dragging

Just upload the code directly.

directives: {
      /*自定义拖拽*/
      drag: {
        inserted: function (el, binding, vnode) {
          var odiv = el.parentNode // 获取元素的父级 也就是这个移动的窗口
          el.onmousedown = function (eve) {
            eve = eve || window.event
            var mx = eve.pageX // 鼠标点击时的x坐标位置
            var my = eve.pageY // 鼠标点击时的y坐标位置
            var dleft = odiv.offsetLeft // 窗口初始的位置
            var dtop = odiv.offsetTop
            var clientWidth = document.documentElement.clientWidth // 页面的宽
            var oWidth = odiv.clientWidth // 窗口的宽度
            var maxX = clientWidth - oWidth // x轴能移动的最大距离
            var clientHeight = document.documentElement.clientHeight // 页面的高
            var oHeight = odiv.clientHeight // 窗口的高度
            var maxY = clientHeight - oHeight // y轴能移动的最大距离
            document.onmousemove = function (e) {
              e.preventDefault()
              var x = e.pageX // 移动时鼠标X坐标
              var y = e.pageY // 移动时鼠标Y坐标
              var left = x - mx + dleft // 移动后对话框新的left值
              var Top = y - my + dtop // 移动后对话框新的Top值
              if (left < 0) {
                left = 0
              }
              if (left > maxX) {
                left = maxX
              }
              if (Top < 0) {
                Top = 0
              }
              if (Top > maxY) {
                Top = maxY
              }
              odiv.style.left = left + 'px'
              odiv.style.top = Top + 'px'
              odiv.style.marginLeft = 0
              odiv.style.marginTop = 0
            }
            document.onmouseup = function () {
              document.onmouseup = ''
              document.onmousemove = ''
            }
          }
        },

Bind this instruction to the child element of the window that needs to be moved, and the style needs to be absolutely positioned

<div class="imgbox">
    <div v-drag class="content"></div>
</div>

 

Guess you like

Origin blog.csdn.net/ringlot/article/details/115248856