使用React js检测用户何时滚动到div的底部
我有一个包含不同部分的网站。我正在使用segment.io来跟踪页面上的不同操作。如何检测用户是否滚动到div的底部?我尝试了以下操作,但似乎在页面上滚动后立即触发,而不是在到达div底部时触发。
componentDidMount() {  document.addEventListener('scroll', this.trackScrolling);
}
trackScrolling = () => {
  const wrappedElement = document.getElementById('header');
  if (wrappedElement.scrollHeight - wrappedElement.scrollTop === wrappedElement.clientHeight) {
    console.log('header bottom reached');
    document.removeEventListener('scroll', this.trackScrolling);
  }
};
回答:
您可以el.getBoundingClientRect().bottom用来检查底部是否已被查看
isBottom(el) {  return el.getBoundingClientRect().bottom <= window.innerHeight;
}
componentDidMount() {
  document.addEventListener('scroll', this.trackScrolling);
}
componentWillUnmount() {
  document.removeEventListener('scroll', this.trackScrolling);
}
trackScrolling = () => {
  const wrappedElement = document.getElementById('header');
  if (this.isBottom(wrappedElement)) {
    console.log('header bottom reached');
    document.removeEventListener('scroll', this.trackScrolling);
  }
};
以上是 使用React js检测用户何时滚动到div的底部 的全部内容, 来源链接: utcz.com/qa/403346.html
