Javascript 你如何使用 jQuery 检测何时接近屏幕底部?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5086401/
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 15:35:37  来源:igfitidea点击:

How do you detect when you're near the bottom of the screen with jQuery?

javascriptjqueryhtmlcss

提问by chrisjlee

I was reading the Harvard Business Review(HBR) blog post , The Traits of Advanced Leaders(2011-02-22). They do this on The New York Times(NYT) too. How do you detect when your reader has scrolled all the way to the bottom?

我正在阅读哈佛商业评论(HBR) 的博客文章高级领导者的特质(2011-02-22)。他们也在纽约时报(NYT)上这样做。您如何检测您的阅读器何时一直滚动到底部?

On HBR, when you scroll the near the bottom, they offer you another article to read.

在 HBR 上,当您滚动底部附近时,他们会为您提供另一篇文章供您阅读。

采纳答案by DrStrangeLove

$(window).scroll(function(){
    if ($(window).scrollTop() == $(document).height()-$(window).height()){
        alert("We're at the bottom of the page!!");
    }
});

回答by Jeff

While the other answer will show you when you are at the bottom, to answer your question about how to tell when you're NEAR the bottom, I've used this before:

虽然另一个答案会告诉您何时处于底部,但要回答有关如何判断何时接近底部的问题,我以前使用过这个:

if  ( ($(document).height() - $(window).height()) - $(window).scrollTop() < 1000 ){
    //do stuff
}

You can change the value "1000" to whatever you want, to trigger your script when you are that many pixels away from the bottom.

您可以将值“1000”更改为您想要的任何值,以便在距离底部那么多像素时触发您的脚本。

回答by Hussein

$(window).scroll(function () {
   if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
      alert('end of page');
   }
});

-10 indicates how far away from end of page user must be before function executes. This gives you the flexibility to adjust the behavior as needed.

-10 表示在函数执行之前用户必须离页面末尾多远。这使您可以根据需要灵活地调整行为。

Check working example at http://jsfiddle.net/wQfMx/

http://jsfiddle.net/wQfMx/检查工作示例