如何使用本机JavaScript实现无限滚动?
在没有任何库或框架的情况下,如何在项目中实现无限/无休止的滚动(如Facebook)如何使用本机JavaScript实现无限滚动?,javascript,dom,dom-events,infinite-scroll,Javascript,Dom,Dom Events,Infinite Scroll,在没有任何库或框架的情况下,如何在项目中实现无限/无休止的滚动(如Facebook) 几乎所有的指南都说明了如何使用jQuery、React和Angular实现无限滚动,但我需要一个用于无限滚动的本机JavaScript实现。这里有一个用本机JavaScript编写的无限/无限滚动代码片段: window.onscroll = function () { if (window.scrollY > (document.body.offsetHeight - window.outerH
几乎所有的指南都说明了如何使用
jQuery
、React
和Angular
实现无限滚动,但我需要一个用于无限滚动的本机JavaScript实现。这里有一个用本机JavaScript编写的无限/无限滚动代码片段:
window.onscroll = function () {
if (window.scrollY > (document.body.offsetHeight - window.outerHeight)) {
console.log("It's working!");
}
}
要为此函数执行添加延迟(如果您必须向服务器发送请求),可以这样编写:
window.onscroll = infiniteScroll;
// This variable is used to remember if the function was executed.
var isExecuted = false;
function infiniteScroll() {
// Inside the "if" statement the "isExecuted" variable is negated to allow initial code execution.
if (window.scrollY > (document.body.offsetHeight - window.outerHeight) && !isExecuted) {
// Set "isExecuted" to "true" to prevent further execution
isExecuted = true;
// Your code goes here
console.log("Working...");
// After 1 second the "isExecuted" will be set to "false" to allow the code inside the "if" statement to be executed again
setTimeout(() => {
isExecuted = false;
}, 1000);
}
}
我在我的ASP.netmvc5
项目中使用了它,它的工作方式很有魅力
注意:
这个代码片段在某些浏览器上不起作用(我正在看你的IE)。IE上的
窗口.scrollY
属性是未定义的。@saifther很抱歉听到这个消息。你确定你正确地实现了它吗?您需要足够的高度才能滚动,以便触发onscroll
事件。您说过它可以与ASP.NET一起使用。。。也许这就是问题所在??!!(我真的不这么认为)@赛义塔,你在使用什么浏览器?我在用谷歌浏览器<代码>窗口。onscroll
事件可能无法在IE、Opera和Safari上正常工作@我可以确认代码片段在Opera上也能正常工作。在IE上它坏了。奇怪的是我也在用Chrome。。。也许我没有正确地实现它,但是:我在JS-Bin上测试了它,而不是在一个正确的HTML文件中