监听父元素的scroll事件

2021-04-02  本文已影响0人  米诺zuo

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

原因分析

根据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 ()
上一篇 下一篇

猜你喜欢

热点阅读