使用 React js 检测用户何时滚动到 div 的底部 [英] Detecting when user scrolls to bottom of div with React js

查看:49
本文介绍了使用 React js 检测用户何时滚动到 div 的底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含不同部分的网站.我正在使用 segment.io 来跟踪页面上的不同操作.如何检测用户是否已滚动到 div 的底部?我尝试了以下操作,但似乎在我滚动页面时立即触发,而不是在我到达了 div 的底部.

I have a website with different sections. I am using segment.io to track different actions on the page. How can I detect if a user has scrolled to the bottom of a div? I have tried the following but it seems to be triggered as soon as I scroll on the page and not when I reached the bottom of the 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检查底部是否被查看

you can use el.getBoundingClientRect().bottom to check if the bottom has been viewed

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 的底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆