如何在没有任何库或框架的情况下在我的项目中实现无限/无限滚动(如Facebook)?
几乎所有指南都展示了如何使用jQuery
,React
和Angular
来做到这一点,但我希望使用原生JavaScript实现无限滚动。
答案 0 :(得分:2)
这是用原生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
。