【问题标题】:How to detect if browser window is scrolled to bottom?如何检测浏览器窗口是否滚动到底部?
【发布时间】:2012-03-15 10:23:25
【问题描述】:

我需要检测用户是否滚动到页面底部。如果它们在页面底部,当我在底部添加新内容时,我会自动将它们滚动到新底部。如果它们不在底部,则它们正在阅读页面上较高的先前内容,因此我不想自动滚动它们,因为它们想留在原处。

如何检测用户是滚动到页面底部还是滚动到页面上方?

【问题讨论】:

  • 这个在 Angular 6 中工作 --> stackoverflow.com/a/42547136/621951

标签: javascript


【解决方案1】:
window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        // you're at the bottom of the page
    }
};

See demo

【讨论】:

  • 当 html/body 元素设置为 100% 时不起作用(这样 body 会填满整个视口高度)
  • 在 IE 中使用 document.documentElement.scrollTop 而不是 window.scrollY。不确定哪个版本的 IE 支持window.scrollY
  • 在 Chromium 版本 47.0.2526.73 中不工作 在 Ubuntu 14.04 上构建,在基本 OS 0.3.2(64 位)上运行
  • 我使用 document.body.scrollHeight 而不是 offsetHeight(在我的例子中,offsetHeight 总是比 window.innerHeight 小)
  • @KarlMorrison 你能用你的浏览器试试赏金答案(@Dekel)吗?
【解决方案2】:

更新了所有主要浏览器支持的代码(包括 IE10 和 IE11)

window.onscroll = function(ev) {
    if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

当前接受的答案的问题是window.scrollY 在 IE 中不可用。

这是来自mdn 关于scrollY 的引用:

为了跨浏览器的兼容性,请使用 window.pageYOffset 而不是 window.scrollY。

还有一个工作的 sn-p:

window.onscroll = function(ev) {
    if ((window.innerHeight + window.pageYOffset ) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

Mac 的注意事项

根据@Raphaël 的评论,由于偏移量小,mac 出现问题。
以下更新的条件有效:

(window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2

我没有机会进一步测试它,如果有人可以就这个特定问题发表评论,那就太好了。

【讨论】:

  • 听起来很奇怪,只是在我的浏览器中我缺少 1 px,因此不会触发条件。不知道为什么,必须添加额外的几个像素才能使其工作。
  • 在mac电脑上,由于偏移量小(~1px),不满足以下条件,我们更新了条件(window.innerHeight + window.pageYOffset) &gt;= document.body.offsetHeight - 2
  • 谢谢@Dekel!实际上,我们发现 window.pageYOffset 在 mac 上是一个浮点数。我们的最终解决方案是(window.innerHeight + Math.ceil(window.pageYOffset + 1)) &gt;= document.body.offsetHeight
  • 不适用于 body 具有将高度设置为 100% 的样式的情况
  • @Raphaël 的评论挽救了我的睡眠!在 mac 中有 1 px 的问题,他的评论真的帮我解决了!!谢谢你!上帝保佑你!
【解决方案3】:

接受的答案对我不起作用。这样做了:

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
      // you're at the bottom of the page
      console.log("Bottom of page");
    }
};

如果您希望支持旧版浏览器 (IE9),请使用别名 window.pageYOffset,它的支持稍好一些。

【讨论】:

  • 在 IE10/11 中不起作用。检查 Dekel 的回答 (stackoverflow.com/questions/9439725/…) 以获得 IE 支持。为我工作
  • 每次我滚动时,其他答案都会触发 console.log(),而不仅仅是当我在页面底部时。这个答案在 Chrome 上对我有用。
  • 如果您摆脱了在 i.e. 或 edge 中不起作用的 window.scrollY,这是一个不错的答案。替换为: (window.innerHeight + window.pageYOffset) >= document.body.scrollHeight
  • 即使您将 body 设置为 100% 的最小高度也可以使用。
  • 同样,这似乎是最好的版本 - 也适用于 mac
【解决方案4】:

我正在寻找答案,但没有找到确切的答案。这是一个纯 javascript 解决方案,可在此答案时与最新的 Firefox、IE 和 Chrome 一起使用:

// document.body.scrollTop alone should do the job but that actually works only in case of Chrome.
// With IE and Firefox it also works sometimes (seemingly with very simple pages where you have
// only a <pre> or something like that) but I don't know when. This hack seems to work always.
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;

// Grodriguez's fix for scrollHeight:
// accounting for cases where html/body are set to height:100%
var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;

// >= is needed because if the horizontal scrollbar is visible then window.innerHeight includes
// it and in that case the left side of the equation is somewhat greater.
var scrolledToBottom = (scrollTop + window.innerHeight) >= scrollHeight;

// As a bonus: how to scroll to the bottom programmatically by keeping the horizontal scrollpos:
// Since window.innerHeight includes the height of the horizontal scrollbar when it is visible
// the correct vertical scrollTop would be
// scrollHeight-window.innerHeight+sizeof(horizontal_scrollbar)
// Since we don't know the visibility/size of the horizontal scrollbar
// we scroll to scrollHeight that exceeds the value of the
// desired scrollTop but it seems to scroll to the bottom with all browsers
// without problems even when the horizontal scrollbar is visible.
var scrollLeft = (document.documentElement && document.documentElement.scrollLeft) || document.body.scrollLeft;
window.scrollTo(scrollLeft, scrollHeight);

【讨论】:

  • 这几乎对我有用,但我不得不使用 ((document.documentElement &amp;&amp; document.documentElement.scrollHeight) || document.body.scrollHeight) 而不仅仅是 document.body.scrollHeight 来解决 html/body 设置为 height:100% 的情况
  • @Grodriguez 感谢您的信息!将来它可能会派上用场! :-)
  • 您的第一条评论使我免于在 Firefox 控制台上与 document.body.scrollTop 进行无意义的斗争。谢谢。
【解决方案5】:

这行得通

window.onscroll = function() {

    // @var int totalPageHeight
    var totalPageHeight = document.body.scrollHeight; 

    // @var int scrollPoint
    var scrollPoint = window.scrollY + window.innerHeight;

    // check if we hit the bottom of the page
    if(scrollPoint >= totalPageHeight)
    {
        console.log("at the bottom");
    }
}

如果您希望支持旧版浏览器 (IE9),请将 window.scrollY 替换为 window.pageYOffset

【讨论】:

  • 这项工作与 2019 年的反应。使用身体 100% 高度,值得与 html 100% 高度。使用 chrome、safari、firefox、edge。
  • 请注意:应更改命名 - 应切换变量。因为scrollHeight显示的是页面总高度,而totalHeight显示的是当前滚动点,所以有点混乱。
【解决方案6】:

如果您在某个容器 &lt;div id="wrapper"&gt; 上设置 height: 100%,则以下代码有效(在 Chrome 中测试):

var wrapper = document.getElementById('wrapper');

wrapper.onscroll = function (evt) {
  if (wrapper.scrollTop + window.innerHeight >= wrapper.scrollHeight) {
    console.log('reached bottom!');
  }
}

【讨论】:

    【解决方案7】:
    window.onscroll = function(ev) {
        if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
            alert("you're at the bottom of the page");
        }
    };
    

    此答案将修复边缘情况,这是因为 pageYOffsetdoubleinnerHeightoffsetHeightlong,所以当浏览器为您提供信息时,您可能是一个像素短。 例如:在页面底部我们有

    window.innerHeight = 10.2

    window.pageYOffset = 5.4

    document.body.offsetHeight = 15.6

    然后我们的计算变成: 10 + 5.4 >= 16 这是 false

    要解决此问题,我们可以对 pageYOffset 值执行 Math.ceil

    希望对您有所帮助。

    【讨论】:

      【解决方案8】:

      我刚开始看这个,这里的答案对我有帮助,所以谢谢你。 我已经扩展了一点,这样代码在 IE7 中一直是安全的:

      希望这对某人有用。

      Here, have a Fiddle ;)

          <!DOCTYPE html>
      <html>
      <head>
          <style>
              div {
                  height: 100px;
                  border-bottom: 1px solid #ddd;
              }
      
              div:nth-child(even) {
                  background: #CCC
              }
      
              div:nth-child(odd) {
                  background: #FFF
              }
      
          </style>
      </head>
      
      <body>
      <div></div><div></div><div></div><div></div><div></div><div></div><div></div>
      <div></div><div></div><div></div><div></div><div></div><div></div><div></div>
      <div></div><div></div><div></div><div></div><div></div><div></div><div></div>
      <div></div><div></div><div></div><div></div><div></div><div></div><div></div>
      <div></div><div></div><div></div><div></div><div></div><div></div><div></div>
      </body>
      
      <script type="text/javascript">
      console.log("Doc Height = " + document.body.offsetHeight);
      console.log("win Height = " + document.documentElement.clientHeight);
      window.onscroll = function (ev) {
          var docHeight = document.body.offsetHeight;
          docHeight = docHeight == undefined ? window.document.documentElement.scrollHeight : docHeight;
      
          var winheight = window.innerHeight;
          winheight = winheight == undefined ? document.documentElement.clientHeight : winheight;
      
          var scrollpoint = window.scrollY;
          scrollpoint = scrollpoint == undefined ? window.document.documentElement.scrollTop : scrollpoint;
      
          if ((scrollpoint + winheight) >= docHeight) {
              alert("you're at the bottom");
          }
      };
      </script>
      </html>
      

      【讨论】:

      • 作品之类的。但这不是很准确。只要您在底部的大约 16px 范围内,它就会认为它滚动到底部。
      【解决方案9】:
      $(document).ready(function(){
          $('.NameOfYourDiv').on('scroll',chk_scroll);
      });
      
      function chk_scroll(e)
      {
          var elem = $(e.currentTarget);
          if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) 
          {
              alert("scrolled to the bottom");
          }
      
      }
      

      【讨论】:

      • idk 不同的视角。但接受的答案肯定更好
      【解决方案10】:

      如果你喜欢 jquery

      $(window).scroll(function() {
        if($(window).scrollTop() + $(window).height() >= $(document).height()) {
          // doSomethingHere();
        }
      });
      

      【讨论】:

      • 还有谁不喜欢 jQuery……
      • @JoshHabdas 浏览器
      【解决方案11】:

      新的解决方案。

      一个问题源于缺少标准的主滚动元素。最近实现的document.scrollingElement 可以用来尝试克服这个问题。下面是一个带回退的跨浏览器解决方案:

      function atEnd() {
          var c = [document.scrollingElement.scrollHeight, document.body.scrollHeight, document.body.offsetHeight].sort(function(a,b){return b-a}) // select longest candidate for scrollable length
          return (window.innerHeight + window.scrollY + 2 >= c[0]) // compare with scroll position + some give
      }
      function scrolling() {
          if (atEnd()) 
              //do something
      }
      window.addEventListener('scroll', scrolling, {passive: true});
      

      【讨论】:

      • 成功了,非常感谢
      【解决方案12】:

      如果您对其他方法不满意,请尝试此方法。

      window.onscroll = function() {
          const difference = document.documentElement.scrollHeight - window.innerHeight;
          const scrollposition = document.documentElement.scrollTop; 
          if (difference - scrollposition <= 2) {
              alert("Bottom of Page!"); 
          }   
      }

      【讨论】:

        【解决方案13】:

        令人惊讶的是,没有一个解决方案对我有用。我认为这是因为我的css 搞砸了,而body 在使用height: 100% 时没有环绕所有内容(还不知道为什么)。然而,在寻找解决方案时,我想出了一些很好的东西......基本相同,但也许值得一看 - 我是编程新手,如果它的速度同样慢,支持较少或类似的东西,我很抱歉那……

        window.onscroll = function(evt) {
          var check = (Element.getBoundingClientRect().bottom - window.innerHeight <= 0) ? true : false;
          if (check) { console.log("You're at the bottom!"); }
        };
        

        【讨论】:

          【解决方案14】:
          const handleScroll = () => {
              if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
                  onScroll();
              }
          };
          

          此代码在 Firefox 和 IE 中也适用于我。

          【讨论】:

            【解决方案15】:

            使用 defaultViewdocumentElement 并嵌入功能代码 sn-p:

            const { defaultView } = document;
            const { documentElement } = document;
            const handler = evt => requestAnimationFrame(() => {
              const hitBottom = (() => (defaultView.innerHeight + defaultView.pageYOffset) >= documentElement.offsetHeight)();
              hitBottom
                ? console.log('yep')
                : console.log('nope')
            });
            document.addEventListener('scroll', handler);
            &lt;pre style="height:110vh;background-color:fuchsia"&gt;scroll down&lt;/pre&gt;

            【讨论】:

              【解决方案16】:

              您可以检查窗口高度和滚动顶部的组合结果是否大于主体的结果

              if (window.innerHeight + window.scrollY &gt;= document.body.scrollHeight) {}

              【讨论】:

                【解决方案17】:

                如上所述,代码可能无法在所有设备和浏览器上运行。以下是经过测试的工作代码,将与所有浏览器(Chrome、IE、Edge、Firefox 和 Safari)中的所有主要设备(iPhone、Android、PC)兼容。

                window.onscroll = function(ev) {
                    var pageHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight,  document.documentElement.clientHeight,  document.documentElement.scrollHeight,  document.documentElement.offsetHeight );
                    if ((window.innerHeight + window.scrollY) >= pageHeight) {
                        console.log("You are at the bottom of the page.");
                    }
                };
                <html>
                <body>
                  <div style="width:100%; height:1500px">
                    <p>Keep scrolling the page till end...</p>
                  </div>
                </body>
                </html>

                【讨论】:

                  【解决方案18】:

                  我发现两个对我有用的解决方案:

                    window.addEventListener('scroll', function(e) {
                      if (
                        window.innerHeight + document.documentElement.scrollTop ===
                        document.documentElement.offsetHeight
                      ) {
                        console.log('You are at the bottom')
                      }
                    })
                  

                  还有一个:

                    window.addEventListener('scroll', function(e) {
                      if (
                        window.innerHeight + window.pageYOffset ===
                        document.documentElement.offsetHeight
                      ) {
                        console.log('You are at the bottom')
                      }
                    })
                  

                  【讨论】:

                  • 我认为您交换了术语顶部和底部。您的解决方案已名列前茅 :-)
                  • 嘿@m3nda,您指的是哪个解决方案?对我来说,两者似乎都在底部开火......
                  • 我尝试了这两种方法,并且在页面顶部(上部内容)与底部相反(当您将整个页面滚动到末尾时)触发了它们。我在 Chrome 和 Firefox 中都检查了一遍。顺便说一句,@Ifeanyi Amadi 的解决方案按预期工作。问候。
                  【解决方案19】:

                  我只是在我的页面底部放置了一个小图像,loading="lazy",这样浏览器只会在用户向下滚动时加载它。然后图像会触发一个返回真实图像的 php 计数器脚本

                   <img loading="lazy" src="zaehler_seitenende.php?rand=<?=rand(1,1000);?>">
                  
                   <?php
                   @header("Location: https://domain.de/4trpx.gif");
                  

                  【讨论】:

                    【解决方案20】:

                    我不得不想出一种方法(在 Java 中)系统地向下滚动以查找我不知道正确 XPath 的组件(长篇大论,所以请继续玩)。正如我刚才所说,我需要在查找组件时向下滚动,并在找到组件或到达页面底部时停止。

                    下面的代码sn-p控制向下滚动到页面底部:

                    JavascriptExecutor js = (JavascriptExecutor) driver;
                    boolean found = false;
                    long currOffset = 0;
                    long oldOffset = 0;
                    do
                    {
                        oldOffset = currOffset;
                        // LOOP to seek the component using several xpath regexes removed
                        js.executeScript("window.scrollBy(0, 100)");
                        currOffset = (Long)js.executeScript("var offset = window.window.pageYOffset; return offset;");
                    } while (!found && (currOffset != oldOffset));
                    

                    顺便说一句,在执行这段代码sn-p之前窗口已经最大化了。

                    【讨论】:

                    • Java 不是 JavaScript。
                    猜你喜欢
                    • 2022-01-19
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2015-04-02
                    • 1970-01-01
                    • 1970-01-01
                    • 2020-07-13
                    相关资源
                    最近更新 更多