Vue实现鼠标拖拽滚动效果,滚动方向不同控制不同组件滚动-自定义指令

横向拖拽滚动

 自定义v-drag指令(横向拖拽滚动)_aら 淼的博客-CSDN博客

vue 有滚动条 点击拖拽滑动自定义指令_高先生的猫的博客-CSDN博客_vue自定义指令滑动

父子组件index与row

index挂载flowDragY,只支持垂直滚动

row挂载flowDragX,鼠标水平移动时支持水平滚动,垂直移动时可以控制index进行垂直滚动

// 定义el
var _el
var _e
Vue.directive('flowDragX', {
  inserted (el, binding, vnode, oldNode) {
    if (!binding) {
      return
    }
    el.onmousedown = e => {
      e.stopPropagation()
        // e.stopPropagation()

      if (e.button === 2) {
        // 右键不管
        return
      }
      //  鼠标按下,计算当前原始距离可视区的高度
      let disX = e.clientX
      let disY = e.clientY
      // index的数据
      // let _disX = _e.clientX
      // let _disY = _e.clientY
      // el.style.cursor = 'move'

      document.onmousemove = function (e) {
        // 移动时禁止默认事件
        // e.preventDefault()
        // e.stopPropagation()

        // row 的数据-------------------
        // left
        const left = e.clientX - disX
        disX = e.clientX
        // el.scrollLeft += -left

        // top
        const top = e.clientY - disY
        disY = e.clientY

        // index的数据--------------------------
        // eslint-disable-next-line no-unused-vars
        // const _left = _e.clientX - _disX
        // _disX = _e.clientX
        // el.scrollLeft += -left

        // top
        // const _top = _e.clientY - _disY
        // _disY = _e.clientY
        // 判断
        // 上下滚动
        if (Math.abs(top) > Math.abs(left)) {
          // console.log('row top1')
          disY = e.clientY
      // 控制index的dom滚动 _el.scrollTop += -top e.preventDefault() } // 左右滚动 if (Math.abs(top) < Math.abs(left)) { disX = e.clientX el.scrollLeft += -left // console.log('row left') e.preventDefault() } } document.onmouseup = function (e) { el.style.cursor = '' document.onmousemove = null document.onmouseup = null e.stopPropagation() direction = false } } } }) Vue.directive('flowDragY', { inserted (el, binding, vnode, oldNode) { _el = el // console.log(binding) if (!binding) { return } if (binding.value.flag) { el.onmousedown = e => { e.stopPropagation() if (e.button === 2) { // 右键不管 return } // 鼠标按下,计算当前原始距离可视区的高度 let disX = e.clientX let disY = e.clientY // el.style.cursor = 'move' document.onmousemove = function (e) { // 移动时禁止默认事件 // e.preventDefault() // e.stopPropagation() _e = e // left const left = e.clientX - disX disX = e.clientX // el.scrollLeft += -left // top const top = e.clientY - disY disY = e.clientY // 判断 if (Math.abs(top) < Math.abs(left)) { direction = true // console.log('left') // e.stopPropagation() } if (Math.abs(top) > Math.abs(left)) { console.log('top') disY = e.clientY el.scrollTop += -top e.preventDefault() direction = false // e.stopPropagation() } } document.onmouseup = function (e) { el.style.cursor = '' document.onmousemove = null document.onmouseup = null // e.stopPropagation() } } } } })

  

posted @ 2022-09-08 15:30  fnasklf  阅读(1035)  评论(0编辑  收藏  举报