如何在没有任何库或框架的情况下在我的项目中实现无限/无限滚动(如Facebook)?
几乎所有指南都展示了如何使用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.NET MVC 5
项目中使用它,它就像一个魅力。
注意:此代码段在某些浏览器上不起作用(我正在看你的IE)。 window.scrollY
属性是IE上的undefined
。