当用户滚动页面底部附近时,Javascript/JQuery 执行功能

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

Javascript/JQuery perform function when user scrolls near bottom of page

javascriptjquery

提问by Chris Sobolewski

On a prominent news site (sry, can't remember exactly which one) I saw a really cool effect... when you scroll near the bottom of the page, a new element slides down from the top of the browser viewport with a lot of social media options (tweet, share on facebook, etc). I'd like to emulate something somewhat similar... in fact, there's really a ton of things I could think of to do if I knew how to trigger a function when the user is near the bottom of the page...

在一个著名的新闻网站上(sry,记不清是哪个了)我看到了一个非常酷的效果......当你滚动到页面底部附近时,一个新元素从浏览器视口的顶部向下滑动社交媒体选项(推文、在 facebook 上分享等)。我想模拟一些有点相似的东西......事实上,如果我知道如何在用户靠近页面底部时触发一个功能,我真的可以想到很多事情要做......

So, my question is very basic: how does one trigger a function when the user has scrolled near the bottom of a dynamically sized page?

所以,我的问题是非常基本的:当用户滚动到动态大小页面的底部附近时,如何触发一个功能?

采纳答案by ctcherry

If you have an element thats near the bottom of the page, you can use Waypointsto trigger a function when the user scrolls to that element. Or if you want to use a pixel limit like in Hussein's post, make sure to heed the scroll lessons we learned from twitter

如果您有一个靠近页面底部的元素,您可以使用Waypoints在用户滚动到该元素时触发一个功能。或者,如果您想使用 Hussein 帖子中的像素限制,请务必注意我们从 twitter 中学到的滚动课程

回答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/检查工作示例