封装一个拖拽

时间:2019-10-25
本文章向大家介绍封装一个拖拽,主要包括封装一个拖拽使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
export default {
  bind: function (el, binding, vnode) {
    const docEl = document.documentElement
    const move = function (e) {
      e.preventDefault()
      if (e.targetTouches.length === 1) {
        const touch = e.targetTouches[0]
        _setPosition(touch)
      }
    }

    function _setPosition (touch) {
      if (touch.clientY <= 40) {
        el.style.top = '0px'
      } else if (touch.clientY > (docEl.clientHeight - el.clientHeight - 47)) {
        el.style.top = (docEl.clientHeight - el.clientHeight - 47) + 'px'
      } else {
        el.style.top = (touch.clientY - (el.clientHeight / 2)) + 'px'
      }
      if (touch.clientX <= 40) {
        el.style.left = '0px'
      } else if (touch.clientX > (docEl.clientWidth - el.clientWidth + 10)) {
        el.style.left = (docEl.clientWidth - el.clientWidth) + 'px'
      } else {
        el.style.left = (touch.clientX - (el.clientWidth / 2)) + 'px'
      }
    }

    const up = function (e) {
      const touch = e.changedTouches[0]

      _setPosition(touch)
      el.removeEventListener('touchmove', move)
      el.removeEventListener('touchend', up)
      binding.value && binding.value()
    }

    const down = function (e) {
      el.addEventListener('touchmove', move, false)
      el.addEventListener('touchend', up, false)
    }

    el.addEventListener('touchstart', down, false)
  }
}

  

原文地址:https://www.cnblogs.com/dhsz/p/11737557.html