如何用纯 JavaScript 实现无限滚动
我想避免使用 jQuery 或其他库,以保持代码最少,我需要的功能很少,我只想在用户滚动到底部时附加到列表。我该如何用普通的 Javascript 来做到这一点?
I want to avoid using jQuery or another library for the sake of keeping my code minimal, I need very little in the way of features, I just want to append to a list when the user scrolls to the bottom. How would I do this in plain Javascript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
基本上你只需要挂钩事件滚动,检查用户是否向下滚动足够,如果是的话添加一些内容:
Basicaly you just need to hook the event scroll, check if the user scrolled down enough and add some content if so:
要实现此行为,您不需要 jQuery 或 jQuery 插件。您可以仅使用 CSS 或 JavaScript(如果您想覆盖所有浏览器)。
但不要使用
onScroll
:您只需使用普通 JS 和 路口观察者 API。您所需要做的就是放置元素并监听它们何时在屏幕上可用。 Intersection Observer API 是高度可定制的,可以满足您的所有需求。
总而言之:您可以通过一些 JavaScript 和 JavaScript 来实现这一点。 HTML 行,它比侦听浏览器中的滚动事件的性能要高得多。
For achieving this behaviour you don't need jQuery or a jQuery plugin. You can use only CSS or JavaScript (if you want to cover all browsers).
But don't use
onScroll
: you can do all of this with just vanilla JS and the Intersection Observer API.All you need to do is place elements and listen for when they become available in the screen. The Intersection Observer API is very customisable to fit all your needs.
In summary: you accomplish that with a few JavaScript & HTML lines and it's much more performant than listening for scroll events in the browser.
优秀的无限滚动演示代码。表明您不需要 jQuery 和 Angular 来进行任何独立于浏览器的工作。但今天的新人已经脱离了我们这些老家伙仍然信任和使用的纯 JavaScript。这里我进一步简化了代码:
Excellent demo code for infinite scroll. Goes to show that you don't need jQuery and Angular for any browser independent work. But new boys today are out of touch with pure Javascript that we old guys still trust and use. Here I have simplified the code further:
并适当处理 evt/scroll 位置。
and handle evt/scroll position appropriately.
我看到了您问题的很好答案,但对于不与任何 HTML 元素或内容关联的滚动(只是一个空的 HTML 页面),我是这样做的:
我希望这对那里的人有帮助:)
I see great answers to your question, but for a scrolling that is not associated with any HTML element or content (just an empty HTML page), here is how I did it:
I hope this helps someone out there :)
实际上@Jan Turon 版本的简化版本对我有用:
Actually a simplified version of @Jan Turon's version worked for me:
假设 HTML:
注意:更重要的部分是:scroll 事件监听器和 loadMoreList 函数。您不一定需要参数 num。
for 循环 只是确保在加载时调用该函数并唯一创建并显示 20 个项目。
Assume HTML:
Note: The more important parts are: the scroll event listener and the loadMoreList function. You don't necessarily need the argument num.
The for loop just ensures that on load, the function is called and 20 items are uniquely created and displayed.