How to do infinite scrolling with javascript only without jquery

前端 未结 6 1014
日久生厌
日久生厌 2021-02-01 10:13

I wish to implement infinite scrolling with javascript and without jquery.

I am new to javascript.

After searching all over the net, I have this code.

         


        
6条回答
  •  梦毁少年i
    2021-02-01 11:08

    first of all i don't think that you have to support netscape and ie6 anymore. So with that in mind I created following script

    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 - 20) {
            var newDiv = document.createElement("div");
            newDiv.innerHTML = "my awesome new div";
            document.getElementById("scroll-content").appendChild(newDiv);
            checkForNewDiv();
        }
    };
    

    also see jsfiddle

提交回复
热议问题