jquery实现加载更多效果

情况是当滑动条滑动到最底部的时候,数据显示出一部分的更多

思路:获取到浏览器屏幕的高度client,文档的高度h和滑动距离顶部的距离scroll,当h<=client+scroll的时候就是滑动条到了底部的时候了,

判断好什么时候到了底部的时候,调取ajax获取到相对应的数据;

代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style>
        *{margin:0px;padding:0px;}
        .content{500px;height:100%;border:1px solid red;margin:10px auto 0px;}
        </style>
    </head>
    <body>
    <div class="content"></div>
    <script src="js/jquery-1.7.2.js"></script>
    <script>
    $(function(){    
        //一开始显示数据
        //实际中应该是将分页的效果做成加载更多的效果 但是调取数据的原理 是一样的 就是显示数据的效果不一样
        ajax();
        $(document).scroll(function(){
            //滚动条滑动的时候获取滚动条距离顶部的距离
            var scroll=$(document).scrollTop();
            //屏幕的高度
            var client=$(window).height();
            var h=$(document).height();
            var flag=true;
            if (h<=scroll+client) { // 到达底部时,加载新内容
                if(flag==false){
                    return;
                }
                ajax();
            }
            
        });
        function ajax(){
            $.ajax({
                url:'https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word,obdata&word=新闻',
                type:'GET',
                dataType:'jsonp',
                success:function(data){
                    flag=false;
                    setTimeout(function(){//只是模拟一下需要有个时间过程表示正在调取数据
                        for(var i=0;i<data.result.length;i++){
                            var result=data.result[i];
                            var odiv='<span style="font-size:35px;margin:10px;line-height:50px;">'+result.word+'</span></br>'+
                                    '<span style="font-size:35px;margin:10px;line-height:50px;">'+result.word+'</span></br>';
                            $(".content").append(odiv);
                        }
                    },500);
                    
                },
            });
        };
        
    });
    </script>
    </body>
</html>

代码地址:https://github.com/GainLoss/load-more

因为加载更多的效果其实作用和分页是一样的 分页的地址:http://www.cnblogs.com/GainLoss/p/5810112.html

原文地址:https://www.cnblogs.com/GainLoss/p/6401146.html