vue 双向滚动条拖动

onMounted(() => {
  const box = document.getElementById('gantt-box')
  let flag, downX, downY, scrollLeft, scrollTop
  box.addEventListener('mousedown', function (event) {
    flag = true;
    [downX, downY, scrollTop, scrollLeft] = [event.clientX, event.clientY, this.scrollTop, this.scrollLeft]
  })
  box.addEventListener('mousemove', function (event) {
    if (flag) { // 判断是否是鼠标按下滚动元素区域
      const [moveX, moveY] = [event.clientX, event.clientY]
      const scrollY = moveY - downY // 当前移动的x轴下标减去刚点击下去的x轴下标得到鼠标滑动距离
      const scrollX = moveX - downX
      this.scrollTop = scrollTop - scrollY // 鼠标按下的滚动条偏移量减去当前鼠标的滑动距离
      this.scrollLeft = scrollLeft - scrollX
    }
  })
  // 鼠标抬起停止拖动
  box.addEventListener('mouseup', function () {
    flag = false
  })
  // 鼠标离开元素停止拖动
  box.addEventListener('mouseleave', function (event) {
    flag = false
  })
})

css部分

    <div id="gantt-box">
      <div class="gantt-auto" />
    </div>

 

css 

#gantt-box {
  width: 1404px;
  height: 530px;
  overflow: auto;
  cursor: grab;
  .gantt-auto {
    width: 2404px;
    height: 1530px;
  }
  &::-webkit-scrollbar-track {
    border-radius: 12px;
    background: none;
    box-shadow: none;
  }
  &::-webkit-scrollbar{
    height: 12px;
    width: 12px;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 12px;
    background: rgba(52, 129, 223, 0.7);
  }
}

 

posted @ 2022-08-01 11:24  王小美丶  阅读(323)  评论(0编辑  收藏  举报