目录

原理图

实现无限分页的过程大致如下:

1.视窗滚动到底部

2.触发加载,添加到现有内容的后面。

因此,可能会出现两种情况:

1.当页面的内容很少,没有出现滚动条。

2.当页面的内容很多,出现了滚动条。

针对这两种情况,需要理解几个概念:

scrollHeight即真实内容的高度;

clientHeight比较好理解,是视窗的高度,就是我们在浏览器中所能看到内容的高度;

scrollTop是视窗上面隐藏掉的部分。

JS - 分页无限加载实例

实现的思路

1.如果真实的内容比视窗高度小,则一直加载到超过视窗

2.如果超过了视窗,则判断下面隐藏的部分的距离是否小于一定的值,如果是,则触发加载。(即滚动到了底部)

代码

1.使用fixed定位加载框

2.使用setTimeout定时触发判断方法,频率可以自定义

3.通过 真实内容高度 - 视窗高度 - 上面隐藏的高度 < 20,作为加载的触发条件。 JS - 分页无限加载实例

<!DOCTYPE html>
<html>
<head>
    <title>无限翻页测试</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <style type="text/css">
    #spinner{
        position: fixed;
        top: 20px;
        left: 40%;
        display: block;
        color: red;
        font-weight: 900;
        background-color: rgba(80, 80, 90, 0.22);
        padding-top: 20px;
        padding-bottom: 20px;
        padding-left: 100px;
        padding-right: 100px;
        border-radius: 15px;
    }
    </style>
</head>
<body>
    <div id="sample">
    </div>
    <div id="spinner">
        正在加载
    </div>
    <script type="text/javascript">
        var index = 0;
        function lowEnough(){
            var pageHeight = Math.max(document.body.scrollHeight,document.body.offsetHeight);
            var viewportHeight = window.innerHeight || 
                document.documentElement.clientHeight ||
                document.body.clientHeight || 0;
            var scrollHeight = window.pageYOffset ||
                document.documentElement.scrollTop ||
                document.body.scrollTop || 0;
            // console.log(pageHeight);
            // console.log(viewportHeight);
            // console.log(scrollHeight);
            return pageHeight - viewportHeight - scrollHeight < 20;
        }

        function doSomething(){
            var htmlStr = "";
            for(var i=0;i<10;i++){
                htmlStr += "这是第"+index+"次加载<br>";
            }
            $('#sample').append(htmlStr);
            index++;
            pollScroll();//继续循环
            $('#spinner').hide();
        }

        function checkScroll(){
            if(!lowEnough()) return pollScroll();

            $('#spinner').show();
            setTimeout(doSomething,900);

        }
        function pollScroll(){
            setTimeout(checkScroll,1000);
        }
        checkScroll();
    </script>
</body>
</html>