Javascript 检查用户是否已滚动到底部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3898130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:34:05  来源:igfitidea点击:

Check if a user has scrolled to the bottom

javascriptjqueryscrollpagination

提问by Johnny

I'm making a pagination system (sort of like Facebook) where the content loads when the user scrolls to the bottom. I imagine the best way to do that is to find when the user is at the bottom of the page and run an ajax query to load more posts.

我正在制作一个分页系统(有点像 Facebook),当用户滚动到底部时会加载内容。我想最好的方法是找到用户何时位于页面底部并运行 ajax 查询以加载更多帖子。

The only problem is I don't know how to check if the user has scrolled to the bottom of the page with jQuery. Any ideas?

唯一的问题是我不知道如何检查用户是否使用 jQuery 滚动到页面底部。有任何想法吗?

I need to find a way to check when the user has scrolled to the bottom of the page with jQuery.

我需要找到一种方法来检查用户何时使用 jQuery 滚动到页面底部。

回答by Nick Craver

Use the .scroll()event on window, like this:

.scroll()上使用事件window,如下所示:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       alert("bottom!");
   }
});

You can test it here, this takes the top scroll of the window, so how much it's scrolled down, adds the height of the visible window and checks if that equals the height of the overall content (document). If you wanted to instead check if the user is nearthe bottom, it'd look something like this:

你可以在这里测试它,这需要窗口的顶部滚动,所以它向下滚动了多少,添加可见窗口的高度并检查它是否等于整体内容的高度 ( document)。如果你想检查用户是否靠近底部,它看起来像这样:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       alert("near bottom!");
   }
});

You can test that version here, just adjust that 100to whatever pixel from the bottom you want to trigger on.

您可以在此处测试该版本,只需将其调整100为您想要触发的底部像素即可。

回答by Miles O'Keefe

Nick Craver's answer works fine, spare the issue that the value of $(document).height()varies by browser.

Nick Craver 的回答工作正常,避免了值$(document).height()因浏览器而异的问题。

To make it work on all browsers, use this function from James Padolsey:

要使其适用于所有浏览器,请使用James Padolsey 的此功能:

function getDocHeight() {
    var D = document;
    return Math.max(
        D.body.scrollHeight, D.documentElement.scrollHeight,
        D.body.offsetHeight, D.documentElement.offsetHeight,
        D.body.clientHeight, D.documentElement.clientHeight
    );
}

in place of $(document).height(), so that the final code is:

代替$(document).height(),所以最终的代码是:

$(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() == getDocHeight()) {
           alert("bottom!");
       }
   });

回答by Félix Gagnon-Grenier

I'm not exactly sure why this has not been posted yet, but as per the documentation from MDN, the simplest way is by using native javascript properties:

我不确定为什么这还没有发布,但根据MDN 的文档,最简单的方法是使用本机 javascript 属性:

element.scrollHeight - element.scrollTop === element.clientHeight

Returns true when you're at the bottom of any scrollable element. So simply using javascript:

当您位于任何可滚动元素的底部时返回 true。所以只需使用javascript:

element.addEventListener('scroll', function(event)
{
    var element = event.target;
    if (element.scrollHeight - element.scrollTop === element.clientHeight)
    {
        console.log('scrolled');
    }
});

scrollHeighthave wide support in browsers, from ie 8 to be more precise, while clientHeightand scrollTopare both supported by everyone. Even ie 6. This should be cross browser safe.

scrollHeight在浏览器中得到广泛支持,从 ie 8 到更精确,而clientHeightscrollTop都受到所有人的支持。即使 ie 6。这应该是跨浏览器安全的。

回答by Tim Carr

For those using Nick's solution and getting repeated alerts / events firing, you could add a line of code above the alert example:

对于那些使用尼克的解决方案并获得重复警报/事件触发的人,您可以在警报示例上方添加一行代码:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       $(window).unbind('scroll');
       alert("near bottom!");
   }
});

This means that the code will only fire the first time you're within 100px of the bottom of the document. It won't repeat if you scroll back up and then back down, which may or may not be useful depending on what you're using Nick's code for.

这意味着代码只会在您第一次到达文档底部 100 像素以内时触发。如果您向上滚动然后向下滚动,它就不会重复,这可能有用也可能没有用,具体取决于您使用 Nick 代码的目的。

回答by George Filippakos

Further to the excellent accepted answer from Nick Craver, you can throttle the scroll event so that it is not fired so frequently thus increasing browser performance:

除了 Nick Craver 出色的公认答案之外,您还可以限制滚动事件,使其不会被频繁触发,从而提高浏览器性能

var _throttleTimer = null;
var _throttleDelay = 100;
var $window = $(window);
var $document = $(document);

$document.ready(function () {

    $window
        .off('scroll', ScrollHandler)
        .on('scroll', ScrollHandler);

});

function ScrollHandler(e) {
    //throttle event:
    clearTimeout(_throttleTimer);
    _throttleTimer = setTimeout(function () {
        console.log('scroll');

        //do work
        if ($window.scrollTop() + $window.height() > $document.height() - 100) {
            alert("near bottom!");
        }

    }, _throttleDelay);
}

回答by Yosi

Nick Craver's answer needs to be slightly modified to work on iOS 6 Safari Mobile and should be:

Nick Craver 的答案需要稍微修改才能在 iOS 6 Safari Mobile 上运行,并且应该是:

$(window).scroll(function() {
   if($(window).scrollTop() + window.innerHeight == $(document).height()) {
       alert("bottom!");
   }
});

Changing $(window).height()to window.innerHeightshould be done because when the address bar is hidden an additional 60px are added to the window's height but using $(window).height()does notreflect this change, while using window.innerHeightdoes.

更改$(窗口).height()window.innerHeight应该做的事,因为当地址栏被隐藏额外的60像素被添加到窗口的高度,但使用$(window).height()没有反映这种变化,同时使用window.innerHeight呢。

Note: The window.innerHeightproperty also includes the horizontal scrollbar's height (if it is rendered), unlike $(window).height()which will not include the horizontal scrollbar's height. This is not a problem in Mobile Safari, but could cause unexpected behavior in other browsers or future versions of Mobile Safari. Changing ==to >=could fix this for most common use cases.

注意:该window.innerHeight属性还包括水平滚动条的高度(如果它被渲染),不同的$(window).height()是不包括水平滚动条的高度。这在 Mobile Safari 中不是问题,但可能会导致在其他浏览器或 Mobile Safari 的未来版本中出现意外行为。对于大多数常见用例,更改==>=可以解决此问题。

Read more about the window.innerHeightproperty here

此处阅读有关该window.innerHeight物业的更多信息

回答by Frederik Witte

Here's a fairly simple approach

这是一个相当简单的方法

const didScrollToBottom = elm.scrollTop + elm.clientHeight == elm.scrollHeight

const didScrollToBottom = elm.scrollTop + elm.clientHeight == elm.scrollHeight

Example

例子

elm.onscroll = function() {
    if(elm.scrollTop + elm.clientHeight == elm.scrollHeight) {
        // User has scrolled to the bottom of the element
    }
}

Where elmis an element retrieved from i.e document.getElementById.

elm从 ie 检索到的元素在哪里document.getElementById

回答by Talon

Here is a piece of code that will help you debug your code, I tested the above answers and found them to be buggy. I have test the followings on Chrome, IE, Firefox, IPad(Safari). I don't have any others installed to test...

这是一段可以帮助您调试代码的代码,我测试了上述答案并发现它们有问题。我在 Chrome、IE、Firefox、iPad(Safari) 上测试了以下内容。我没有安装任何其他人来测试...

<script type="text/javascript">
   $(function() {
      $(window).scroll(function () {
         var docElement = $(document)[0].documentElement;
         var winElement = $(window)[0];

         if ((docElement.scrollHeight - winElement.innerHeight) == winElement.pageYOffset) {
            alert('bottom');
         }
      });
   });
</script>

There may be a simpler solution, but I stopped at the point at which IT WORKED

可能有一个更简单的解决方案,但我在它起作用的时候停了下来

If you are still having problems with some rogue browser, here is some code to help you debug:

如果您仍然遇到某些流氓浏览器的问题,这里有一些代码可以帮助您调试:

<script type="text/javascript">
   $(function() {
      $(window).scroll(function () {
         var docElement = $(document)[0].documentElement;
         var details = "";
         details += '<b>Document</b><br />';
         details += 'clientHeight:' + docElement.clientHeight + '<br />';
         details += 'clientTop:' + docElement.clientTop + '<br />';
         details += 'offsetHeight:' + docElement.offsetHeight + '<br />';
         details += 'offsetParent:' + (docElement.offsetParent == null) + '<br />';
         details += 'scrollHeight:' + docElement.scrollHeight + '<br />';
         details += 'scrollTop:' + docElement.scrollTop + '<br />';

         var winElement = $(window)[0];
         details += '<b>Window</b><br />';
         details += 'innerHeight:' + winElement.innerHeight + '<br />';
         details += 'outerHeight:' + winElement.outerHeight + '<br />';
         details += 'pageYOffset:' + winElement.pageYOffset + '<br />';
         details += 'screenTop:' + winElement.screenTop + '<br />';
         details += 'screenY:' + winElement.screenY + '<br />';
         details += 'scrollY:' + winElement.scrollY + '<br />';

         details += '<b>End of page</b><br />';
         details += 'Test:' + (docElement.scrollHeight - winElement.innerHeight) + '=' + winElement.pageYOffset + '<br />';
         details += 'End of Page? ';
         if ((docElement.scrollHeight - winElement.innerHeight) == winElement.pageYOffset) {
             details += 'YES';
         } else {
             details += 'NO';
         }

         $('#test').html(details);
      });
   });
</script>
<div id="test" style="position: fixed; left:0; top: 0; z-index: 9999; background-color: #FFFFFF;">

I hope this will save someone some time.

我希望这会为某人节省一些时间。

回答by Junaid Qadir

Please check this answer

请检查这个答案

 window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
       console.log("bottom");
    }
};

You can do footerHeight - document.body.offsetHeightto see if you are near the footer or reached the footer

你可以footerHeight - document.body.offsetHeight看看你是在页脚附近还是到达了页脚

回答by Vasyl Gutnyk

var elemScrolPosition = elem.scrollHeight - elem.scrollTop - elem.clientHeight;

It calculates distance scroll bar to bottom of element. Equal 0, if scroll bar has reached bottom.

它计算滚动条到元素底部的距离。等于 0,如果滚动条已到达底部。