【问题标题】:How to detect if browser window is "near" the bottom?如何检测浏览器窗口是否“靠近”底部?
【发布时间】:2022-01-19 13:42:26
【问题描述】:

我正在为我的 react 应用程序使用无限滚动,并且有这个功能可以检测我何时正好位于页面底部:

const [isFetching, setIsFetching] = useState(false);

// Fire Upon Reaching the Bottom of the Page
  const handleScroll = () => {
    if (
      window.innerHeight +
        Math.max(
          window.pageYOffset,
          document.documentElement.scrollTop,
          document.body.scrollTop
        ) !==
      document.documentElement.offsetHeight
    )
      return;

    setIsFetching(true);
  };

  // Debounce the Scroll Event Function and Cancel it When Called
  const debounceHandleScroll = debounce(handleScroll, 100);

  useEffect(() => {
    window.addEventListener("scroll", debounceHandleScroll);
    return () => window.removeEventListener("scroll", debounceHandleScroll);
  }, [debounceHandleScroll]);

  debounceHandleScroll.cancel();

问题在于当我在手机中加载我的页面时,似乎由于移动浏览器的标签或栏,它没有检测到页面底部,因此内容没有加载。

有什么方法可以检测到用户靠近底部并在那时才触发该功能?

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    我认为 IntersectionObserver 可能是您正在寻找的。 您可以查看本教程了解基本信息:https://dev.to/producthackers/intersection-observer-using-react-49ko

    你也可以把它变成一个自定义钩子,它接受一个 ref(在你的例子中,你页面底部的一个 n 元素):

    import { useEffect, useState } from 'react';
    
    const useIsVisible = ref => {
      const [isIntersecting, setIntersecting] = useState(false);
    
      const observer = new IntersectionObserver(([entry]) =>
        setIntersecting(entry.isIntersecting),
      );
    
      useEffect(() => {
        observer.observe(ref.current);
    
        return () => {
          observer.disconnect();
        };
      }, []);
    
      return isIntersecting;
    };
    
    export default useIsVisible;
    

    也许下面的包也可以帮助你,它使实现无限滚动变得非常容易:

    https://www.npmjs.com/package/react-infinite-scroll-component

    【讨论】:

    • 感谢您的回答。有什么办法可以用纯 JS 做到这一点?我真的没有时间改变目前的一切
    • Intersection Observer 不是 React 自己的功能。它是浏览器 API,因此您可以在 vanilla JS 中使用 IO
    【解决方案2】:

    我设法将滚动功能更改为这个,现在它可以工作了。

      const handleScroll = () => {
        if (
          window.innerHeight +
            Math.max(
              window.pageYOffset,
              document.documentElement.scrollTop,
              document.body.scrollTop
            ) >
          document.documentElement.offsetHeight - 100
        ) {
          setIsFetching(true);
        } else {
          return;
        }
      };
    

    document.documentElement.offsetHeight 减少的数字决定了页面底部的剩余数量。 100 对我来说似乎足够了,因为我在手机上测试过它并且它有效。

    【讨论】:

      猜你喜欢
      • 2012-03-15
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      相关资源
      最近更新 更多