如何在纯 Javascript 中进行无限滚动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6456846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do an infinite scroll in plain Javascript
提问by Abhinav Sharma
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?
为了保持我的代码最少,我想避免使用 jQuery 或其他库,我需要的功能很少,我只想在用户滚动到底部时附加到列表中。我将如何在纯 Javascript 中执行此操作?
回答by Jan Turoň
Basicaly you just need to hook the event scroll, check if the user scrolled down enough and add some content if so:
基本上你只需要钩住事件滚动,检查用户是否向下滚动,如果是的话,添加一些内容:
<html><body>
<div id="test">scroll to understand</div>
<div id="wrapper" style="height: 400px; overflow: auto;">
<div id="content"> </div>
</div>
<script language="JavaScript">
// we will add this content, replace for anything you want to add
var more = '<div style="height: 1000px; background: #EEE;"></div>';
var wrapper = document.getElementById("wrapper");
var content = document.getElementById("content");
var test = document.getElementById("test");
content.innerHTML = more;
// cross browser addEvent, today you can safely use just addEventListener
function addEvent(obj,ev,fn) {
if(obj.addEventListener) obj.addEventListener(ev,fn,false);
else if(obj.attachEvent) obj.attachEvent("on"+ev,fn);
}
// this is the scroll event handler
function scroller() {
// print relevant scroll info
test.innerHTML = wrapper.scrollTop+"+"+wrapper.offsetHeight+"+100>"+content.offsetHeight;
// add more contents if user scrolled down enough
if(wrapper.scrollTop+wrapper.offsetHeight+100>content.offsetHeight) {
content.innerHTML+= more;
}
}
// hook the scroll handler to scroll event
addEvent(wrapper,"scroll",scroller);
</script>
</body></html>
回答by Nairit
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:
无限滚动的优秀演示代码。表明您不需要 jQuery 和 Angular 来进行任何浏览器独立的工作。但是今天的新人已经与我们老人们仍然信任和使用的纯 Javascript 脱节了。这里我进一步简化了代码:
<html>
<head>
<script language="JavaScript">
// we will add this content, replace for anything you want to add
var wrapper, content, test;
var more = '<div style="height:1000px; background:#EEE;"></div>';
// this is the scroll event handler
function scroller()
{
// print relevant scroll info
test.innerHTML = wrapper.scrollTop + " + " + wrapper.offsetHeight + " + 100 > " + content.offsetHeight;
// add more contents if user scrolled down enough
if(wrapper.scrollTop + wrapper.offsetHeight + 100 > content.offsetHeight)
{
content.innerHTML += more; // NK: Here you can make an Ajax call and fetch content to append to content.innerHTML
}
}
</script>
</head>
<body>
<div id="test">scroll to understand</div>
<div id="wrapper" style="height: 400px; overflow: auto;">
<div id="content"> </div>
</div>
<script language="JavaScript">
wrapper = document.getElementById("wrapper");
content = document.getElementById("content");
test = document.getElementById("test");
content.innerHTML = more;
// hook the scroll handler to scroll event
if(wrapper.addEventListener) // NK: Works on all new browsers
wrapper.addEventListener("scroll",scroller,false);
else if(wrapper.attachEvent) // NK: Works on old IE
wrapper.attachEvent("onscroll",scroller);
</script>
</body>
</html>
回答by Giddy Naya
Sample snippet with cross browser support: Read inline comments for how it works
具有跨浏览器支持的示例片段: Read inline comments for how it works
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
//User is currently at the bottom of the page
addNewItem();
}
};
function addNewItem(){
var itemCount = document.getElementById("movieList").childElementCount;
const itemLimit = 10; //total number of items to retrieve
//retrieve the next list of items from wherever
var nextTopItems = getNextItemSimulator(itemCount);
nextTopItems.forEach(function(item) {
//add the items to your view
document.getElementById("movieList").innerHTML += "<p>"+item+"</p>";
document.getElementById("footer").style.display = "block";
});
setTimeout(function(){
//remove footer info message
document.getElementById("footer").style.display = "none";}, 500);
}
function getNextItemSimulator(currentItem){
//Just some dummy data to simulate an api response
const dummyItemCount = 50;
var dummyItems = [];
var nextTopDummyItems = [];
for(i = 1; i <= dummyItemCount; i++){
//add to main dummy list
dummyItems.push("Movie " + i);
}
var countTen = 10;
var nextItem = currentItem + 1;
for(i = nextItem; i <= dummyItems.length; i++){
//get next 10 records from dummy list
nextTopDummyItems.push(dummyItems[i - 1]);
countTen--;
if(countTen == 0)break;
}
return nextTopDummyItems;
}
#footer {
position: fixed;
bottom: 0;
width: 100%;
display:none;
background: #eee;
}
#movieList{
margin-bottom: 20px;
}
<h3> Movies 2019 </h3>
<div id="movieList">
<p>Movie 1</p>
<p>Movie 2</p>
<p>Movie 3</p>
<p>Movie 4</p>
<p>Movie 5</p>
<p>Movie 6</p>
<p>Movie 7</p>
<p>Movie 8</p>
<p>Movie 9</p>
<p>Movie 10</p>
</div>
<div id="footer">Loading more movies</div>
回答by Fouad Boukredine
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:
我看到了您的问题的很好的答案,但是对于与任何 HTML 元素或内容(只是一个空的 HTML 页面)无关的滚动,我是这样做的:
document.querySelector("body").style.height = "1000px";
window.addEventListener("scroll", function() {
var body = document.querySelector("body");
var height = body.style.height;
height = height.slice(0, -2);
height = Number(height);
return function() {
if(height - window.scrollY < 700) {
height += height / 2;
}
body.style.height = height + "px";
};
}());
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
I hope this helps someone out there :)
我希望这可以帮助那里的人:)
回答by c-smile
domElem.addEventListener(
'scroll',
function(evt) { ... },
false
);
and handle evt/scroll position appropriately.
并适当处理 evt/scroll 位置。