首页 > 代码库 > 滚动加载

滚动加载

<!doctype html>
<html lang="en">

    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
        <style type="text/css">
            html {
                font-size: 20px;
            }
            #main{
                width: 800px;
                height: 400px;
                overflow: scroll;
            }
            #target {
                width: 300px;
                height: 1000px;
                margin: 40px auto;
                box-sizing: border;
                border: 100px solid #aaa;
                background-color: #ccc;
                text-align: center;
                line-height: 1000px;
                font-size: 40px;
            }
        </style>
    </head>

    <body>
        <div id="main">
            <div id="target">
                target content
            </div>
        </div>
        <script type="text/javascript">
            var obj = {
                is_loading: false,  
            };

            // 游缆器滚动事件  
            document.getElementById("main").onscroll = function() {
                if(ui_is_screen_bottom() && !obj.is_loading) {
                    obj.is_loading = true;
                    load_ajax_data();
                }
            }
            //模拟加载Ajax数据  
            function load_ajax_data() {
                if(ui_is_screen_bottom() && !obj.is_loading) {
                    console.log(正在加载);
                }else{
                    console.log(加载数据);
                }
            }
            //判断是滚动到页面底部  
            function ui_is_screen_bottom() {
                var ele = document.getElementById("main");
                var scrollTop = 0;
                var clientHeight = 0;
                var scrollHeight = 0;
                scrollTop = ele.scrollTop;
                clientHeight = ele.offsetHeight;
                scrollHeight = ele.scrollHeight;
                
                if(scrollTop + clientHeight >= scrollHeight-20) {

                    return true;
                } else {
                    return false;
                }
            }
        </script>
    </body>

</html>

 

滚动加载