横向滚动和纵向滚动能做不同的监听吗?

同一元素有横向和纵向滚动,只想对纵向滚动做防抖

阅读 1.5k
2 个回答

思路是横向滚动scrollTop不会变化, 对做监听scrollTop, 需要做的防抖处理在这里做
image.png

<template>
  <div>
    <div
      class="horizontal-scroll-wrapper"
      id="fixed"
    >
      <div class="item1">item 1</div>
      <div>item 2</div>
      <div>item 3</div>
      <div>item 4</div>
      <div>item 5</div>
      <div>item 6</div>
      <div>item 7</div>
      <div>item 8</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'index',
  data () {
    return {
      scrollTop: 0
    }
  },
  watch : {
    scrollTop (newVal, oldVal) {
      console.log(2);
    }
  },
  mounted () {
    var fixedDom = document.getElementById('fixed');
    var items = fixedDom.querySelectorAll('.item1')

    console.dir(fixedDom);
    fixedDom.addEventListener('scroll', (event) => {
      const { scrollTop } = event.target;  // 获取当前滚动条的水平偏移量
      const visibleItems = [];

      // for (let i = 0; i < items.length; i++) {
      //   const item = items[i];
      //   const itemRect = item.getBoundingClientRect();  // 获取子元素相对视窗的位置信息
      //   if (itemRect.left >= scrollLeft && itemRect.right <= scrollLeft + fixedDom.clientWidth) {
      //     visibleItems.push(item);
      //   }
      // }
      this.scrollTop = scrollTop
      console.log(`容器水平偏移量:${scrollTop},可见子元素有:`, visibleItems);
    });
  },

}
</script>

<style lang="css" scoped>
.horizontal-scroll-wrapper {
  width: 500px;
  display: flex;
  background: #abc;
  overflow-x: auto;
  gap: 10px;
  height: 100px;
}

.horizontal-scroll-wrapper > div {
  display: block;
  background: #cab;
  width: 100px;
  height: 250px;
  flex-shrink: 0;
}
</style>

可以通过滚动事件对象的 deltaXdeltaY 属性值来判断。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题