监听父元素的scroll事件

一开始,想着在 window / document 上绑定scroll事件,发现不起作用。

原因分析

  • 需要明白当前滚动的事件的是发生于哪个页面
  • 只有当父元素不够显示当前内容时浏览器才会发生滚动
  • 页面的滚动事件可能位于wrapper的父级身上,监听window也就不会触发事件

根据MDNscroll事件的描述:

冒泡: element的scroll事件不冒泡, 但是document的defaultView的scroll事件冒泡

当元素外面的scroll滚动时, 可能造成element位置移动

 onScrollEvent = () => {
   // do something when scroll 
  }

  bindScrollEvent = (ref) => {
    if (this.scrollNode.length) return
    let node = ref
    while (node.parentElement) {
      node = node.parentElement
      node.addEventListener("scroll", this.onScrollEvent);
      this.scrollNode.push(node)
    }
  }

  unbindScrollEvent = () => {
    for (const node of this.scrollNode) {
      node.removeEventListener("scroll", this.onScrollEvent);
    }
    this.scrollNode = []
  }

// 绑定scroll事件

 this.bindScrollEvent(this.demoRef.current)

// 移除scroll事件

this.unbindScrollEvent ()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容