如何在普通的Javascript中进行无限滚动

时间:2011-06-23 15:43:22

标签: javascript firefox scroll infinite-scroll

我想避免使用jQuery或其他库来保持我的代码最小化,我只需要很少的功能,我只想在用户滚动到底部时附加到列表。我如何在普通的Javascript中执行此操作?

6 个答案:

答案 0 :(得分:9)

基本上你只需要挂钩事件滚动,检查用户是否向下滚动并添加一些内容,如果是这样的话:

<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>

答案 1 :(得分:2)

无限滚动的优秀演示代码。这表明您不需要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>

答案 2 :(得分:2)

为了实现这种行为,您不需要 jQuery 或 jQuery 插件。您只能使用 CSS 或 JavaScript(如果您想覆盖所有浏览器)。

但不要使用 onScroll:您可以只使用 vanilla JS 和 Intersection Observer API 来完成所有这些。

您需要做的就是放置元素并在它们在屏幕上可用时进行监听。 Intersection Observer API 可高度自定义以满足您的所有需求。

总而言之:您只需使用几行 JavaScript 和 HTML 代码即可实现这一点,而且它比在浏览器中侦听滚动事件的性能要高得多。

答案 3 :(得分:1)

domElem.addEventListener(
        'scroll',
        function(evt) { ... },
        false
    ); 

并适当处理evt / scroll位置。

答案 4 :(得分:0)

具有跨浏览器支持的示例代码段: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>

答案 5 :(得分:0)

对于您的问题,我看到了很好的答案,但是对于与任何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>

我希望这可以帮助某个人:)