只监听父元素的滚动事件,而不监听子元素的滚动事件

第一种,JS

1、判断dom

this.$refs.squareRef.addEventListener('wheel', this.addScrolbarFn, false)

addScrolbarFn(event) {
  event.stopPropagation()
  const dom = this.$refs?.rightResultRef?.$refs?.resultDiv
  if (event.target === this.$refs?.squareRef) {
    const goFlag = dom?.scrollTop + dom.clientHeight === dom.scrollHeight ? true : false
    // 上滚 && 不在顶部
    if (event?.deltaY < 0 && dom.scrollTop !== 0) {
      const scrollHeight = dom.scrollTop - 100
      dom?.scrollTo(0, scrollHeight)
    } else if (event?.deltaY > 0 && !goFlag) {
      const scrollHeight = dom.scrollTop + 100
      dom?.scrollTo(0, scrollHeight)
    }
  }
},

this.$refs.squareRef.removeEventListener('wheel', this.addScrolbarFn)

2、子元素阻止冒泡

<div id="parentEl" @wheel="handleScroll">
  <div id="childEl" @wheel="handleChildScroll"></div>
</div>

<script>
var parentEl = document.querySelector('#parentEl');
var childEl = document.querySelector('#childEl');

function handleScroll(event) {
  console.log('父元素滚动');
}

function handleChildScroll(event) {
  event.stopPropagation();
  console.log('子元素滚动');
}
</script>

第二种,vue 监听器配合修饰符

posted @ 2023-04-26 15:54  DL·Coder  阅读(133)  评论(0编辑  收藏  举报