web前端开发常用上拉刷新demo,代码可直接运行

JavaScript/前端
296
0
0
2022-04-14

web前端开发常用上拉刷新demo,代码可直接运行

前端开发过程中常用的上拉刷新demo,下拉刷新与此原理类似

界面如下(有点丑的demo哈):

web前端开发常用上拉刷新demo,代码可直接运行

代码如下如示:

web前端开发常用上拉刷新demo,代码可直接运行

web前端开发常用上拉刷新demo,代码可直接运行

<style>
    *{
        padding: 0;
        margin: 0;
    }
    .box{
        height: 100%;
        /* overflow: hidden auto; */
    }
    #refreshContainer{
        width: 90%;
        margin: 0 auto;
    }
    ul li{
        outline-style: none;
        outline: none;
    }
    #refreshContainer li{
        height: 60px;
        line-height: 60px;
        padding: 0 10px;
        background: green;
        margin: 10px auto;
        list-style:none;
    }
</style>
</head>
<body>
<div class="box"> 
    <ul id="refreshContainer"> 
        <li>111</li> 
        <li>222</li> 
        <li>333</li> 
        <li>444</li> 
        <li>555</li> 
        <li>111</li> 
        <li>222</li> 
        <li>333</li> 
        <li>444</li> 
        <li>555</li> 
    </ul> 
    <p class="refreshText"></p>
</div>
</body>
<script>
    (function(window) {
        // 获取当前滚动条的位置 
        function getScrollTop() {
            var scrollTop = 0;
            if (document.documentElement && document.documentElement.scrollTop) {
                scrollTop = document.documentElement.scrollTop;
            } else if (document.body) {
                scrollTop = document.body.scrollTop;
            }
            return scrollTop;
        }
        // 获取当前可视范围的高度 
        function getClientHeight() {
            var clientHeight = 0;
            if (document.body.clientHeight && document.documentElement.clientHeight) {
                clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
            }
            else {
                clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
            }
            return clientHeight;
        }
        // 获取文档完整的高度 
        function getScrollHeight() {
            return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
        }
        var _text = document.querySelector('.refreshText'),
            _container = document.getElementById('refreshContainer');
        // 节流函数 
        var throttle = function(method, context){
            clearTimeout(method.tId);
            method.tId = setTimeout(function(){
                method.call(context);
            }, 300);
        }
        function fetchData() {
            setTimeout(function() {
                _container.insertAdjacentHTML('beforeend', '<li>new add...</li>');
            }, 1000);
        }
        window.onscroll = function() {
            if (getScrollTop() + getClientHeight() == getScrollHeight()) {
                _text.innerText = '加载中...';
                throttle(fetchData);
            }
        };
    })(window);
</script>

代码可直接复制

每日一分享,感谢所有关注的粉丝们