Javascript Infinite Scroll in div [英] Javascript Infinite Scroll inside a div
问题描述
我正在尝试使用javascript创建无限加载页面。我发现了这个:如何在没有jquery的情况下使用javascript进行无限滚动
I am trying to create an infinite loading page with the use of javascript. I found this: How to do infinite scrolling with javascript only without jquery
我一直在玩最后一个链接到这个jsfiddle页面的答案: http://jsfiddle.net/8LpFR/
I have been playing with the last answer that links to this jsfiddle page: http://jsfiddle.net/8LpFR/
document.addEventListener("scroll", function (event) {
checkForNewDiv();
});
var checkForNewDiv = function () {
var lastDiv = document.querySelector("#scroll-content > div:last-child");
var lastDivOffset = lastDiv.offsetTop + lastDiv.clientHeight;
var pageOffset = window.pageYOffset + window.innerHeight;
if (pageOffset > lastDivOffset - 10) {
var newDiv = document.createElement("div");
newDiv.innerHTML = "my awesome new div";
document.getElementById("scroll-content").appendChild(newDiv);
checkForNewDiv();
}
};
checkForNewDiv();
我如何修改它以使滚动工作在div内而不是整个页面?如同,lastDivOffset和pageoffset会变为什么?
How would I modify that in order to make the scrolling work inside a div rather than as the whole page? As in, what would lastDivOffset and pageoffset change to?
推荐答案
以下是没有创建任何新包装器的解决方案。
Here is the solution without creating any new wrapper division.
document.getElementById("scroll-content").addEventListener("scroll", function(event) {
var newDiv = document.createElement("div");
newDiv.innerHTML = "my awesome new div";
document.getElementById("scroll-content").appendChild(newDiv);
});
var checkForNewDiv = function() {
var lastDiv = document.querySelector("#scroll-content > div:last-child");
var maindiv = document.querySelector("#scroll-content");
var lastDivOffset = lastDiv.offsetTop + lastDiv.clientHeight;
var pageOffset = maindiv.offsetTop + maindiv.clientHeight;
if (pageOffset > lastDivOffset - 10) {
var newDiv = document.createElement("div");
newDiv.innerHTML = "my awesome new div";
document.getElementById("scroll-content").appendChild(newDiv);
checkForNewDiv();
}
};
checkForNewDiv();
这篇关于Javascript Infinite Scroll in div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!