无限滚动设置的超级简单实现总结

2025-06-10

无限滚动的超级简单实现

设置

总结

我想在https://sideprojects.net上分享我们使用 jQuery 实现无限滚动的方法以及如何将其应用于其他网站。

在我们的例子中,我们的分页采用“加载更多”格式,每次到达页面底部时,您都必须单击“加载接下来的几天”按钮才能显示前 4 天的内容。

我们想要做的是,当您滚动到页面底部时显示接下来的几天,这就是本教程将介绍的内容。

设置

先决条件

  • 具有某种分页功能的网站。
  • 如果您还没有添加 jQuery,请将其添加到您的网站。


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">


Enter fullscreen mode Exit fullscreen mode
  • 如果您还没有类,请向控制您网站分页的按钮添加一个类。

1)创建窗口滚动事件



//Infinite scroll
$(window).on("scroll", function() {

});


Enter fullscreen mode Exit fullscreen mode

2)创建一个用于存储整个文档高度的变量以及一个用于确定滚动位置的变量

在滚动事件中,创建两个变量。我们分别命名为 scrollHeight 和 scrollPos。



var scrollHeight = $(document).height();
var scrollPos = $(window).height() + $(window).scrollTop();


Enter fullscreen mode Exit fullscreen mode

3)让我们做一些数学题吧!

记住:我们希望每次用户滚动到页面底部时触发该事件。

我们可以使用以下条件语句检查您是否已到达页面底部:



if ((scrollHeight - scrollPos) / scrollHeight == 0) {


Enter fullscreen mode Exit fullscreen mode

我们希望在满足条件语句时触发事件。

在我们的例子中,按钮的类名是 .load-more-days-button。到达页面末尾时,该按钮将被点击。



if ((scrollHeight - scrollPos) / scrollHeight == 0) {             
   $('.load-more-days-button').click();
}


Enter fullscreen mode Exit fullscreen mode

综合起来,我们得到:



//Infinite scroll
$(window).on("scroll", function() {
  var scrollHeight = $(document).height();
  var scrollPos = $(window).height() + $(window).scrollTop();
  if ((scrollHeight - scrollPos) / scrollHeight == 0) {
    $('.load-more-days-button').click();
    console.log("bottom!");
  }
});


Enter fullscreen mode Exit fullscreen mode

就这些?完了吗?!嗯——是的,但又不是。

有用。

但效果并不好。为什么呢?

  1. 它要求您一直向下滚动,以便滚动条在触发事件之前触及末端。
  2. 它在移动设备上效果很差。我注意到,它并不总是在移动设备上触发,即使你已经滚动到页面底部,它也不会检测到你已到达页面底部。

因此让我们修复它:

让我们替换这一行:



if ((scrollHeight - scrollPos) / scrollHeight == 0) {


Enter fullscreen mode Exit fullscreen mode

改为:



if(((scrollHeight - 300) >= scrollPos) / scrollHeight == 0) {


Enter fullscreen mode Exit fullscreen mode

这行代码使 scroll 事件在距离页面底部 300 像素(或更少)时触发。(如果您愿意,可以将 300 像素配置为其他值)

这在桌面和移动设备上效果很好!

总结

将所有内容放在一起,您的代码最终可能看起来像这样:



//Infinite Scroll
$(window).on("scroll", function() {
 //page height
 var scrollHeight = $(document).height();
 //scroll position
 var scrollPos = $(window).height() + $(window).scrollTop();
 // fire if the scroll position is 300 pixels above the bottom of the page
 if(((scrollHeight - 300) >= scrollPos) / scrollHeight == 0){
   $('.load-more-days-button').click();
  }
});


Enter fullscreen mode Exit fullscreen mode

您可以在此处查看实例

鏂囩珷鏉ユ簮锛�https://dev.to/sakun/a-super-simple-implementation-of-infinite-scrolling-3pnd
PREV
项目式学习的优势:它与课程式学习有何不同?🧐 优点 🎉 缺点 🚨 结论 😎
NEXT
不要太依赖 useState,useRef 可以帮你