vue实现遍历渲染可拖拽dom

function drag (el, binding, vnode) {
  el.onmousedown = function (event) {
    const x = event.pageX - el.offsetLeft
    const y = event.pageY - el.offsetTop

    const dragDomWidth = el.offsetWidth
    const dragDomHeight = el.offsetHeight

    const screenWidth = document.body.scrollWidth
    const screenHeight = binding.value || document.body.clientHeight

    const minDragDomLeft = 0
    const maxDragDomLeft = screenWidth - dragDomWidth

    const minDragDomTop = 0
    const maxDragDomTop = screenHeight - dragDomHeight

    document.onmousemove = function (event) {
      let top = event.pageY - y
      let left = event.pageX - x

      if (top < minDragDomTop) {
        top = minDragDomTop
      } else if (top > maxDragDomTop) {
        top = maxDragDomTop
      }

      if (left < minDragDomLeft) {
        left = minDragDomLeft
      } else if (left > maxDragDomLeft) {
        left = maxDragDomLeft
      }

      el.style.left = left + 'px'
      el.style.top = top + 'px'

      vnode.context.$emit('move', {
        top,
        left
      })
    }

    document.onmouseup = function () {
      vnode.context.$emit('drag-end', {
        top: el.style.top,
        left: el.style.left
      })
      document.onmousemove = null
      document.onmouseup = null
    }
  }
}

export default {
  bind: drag
}

组件





你可能感兴趣的:(vue实现遍历渲染可拖拽dom)