JQ - 实现元素滚动下拉加载

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            ul{
                width:200px;
                height: 600px;
                border: 1px solid #000;
                margin: 40px auto;
                overflow: overlay;
                -webkit-overflow-scrolling: touch;
            }
            li{
                list-style: none;
                width:100%;
                height: 200px;
                background: skyblue;
                margin: 20px 0;
            }
            
        </style>
    </head>
    <body>
        <ul dynamicLoad ></ul>  <!-- $dom -->
        
        <script src='https://code.jquery.com/jquery-3.1.1.min.js'></script>
        <script>
    
        $(function(){

            let pageNum = 1; // 初始页
            let pageMax = 5; // 最大页数
            let $dom = $('[dynamicLoad]'); 
let dynamicLoad
= new DynamicLoad({ $dom: $dom, pageNum: pageNum, pageMax: pageMax, onPage: function(page) { console.log('切换到第'+page+'页'); dynamicLoad.loading('正在加载,请稍候...'); // 显示加载提示 setTimeout(function(){ // 加载完成 渲染的数据 dynamicLoad.onload(` <li> new 1 </li> <li> new 2 </li> <li> new 3 </li> `) }, 500) } }) // 重置 初始页,最大页,html dynamicLoad.reset({ pageNum:1, pageMax:3, html:` <li>1</li> <li>2</li> <li>3</li> <li>4</li> ` }) }) class DynamicLoad { constructor({ $dom, pageNum, pageMax, onPage }) { let that = this // 绑定this this.pageNum = pageNum; // 初始页 this.pageMax = pageMax; // 最大页码 this.onPage = onPage; // this.$dom = $dom; // dom this.$tips = $('<p class="end">上拉加载更多</p>'); // 加载提示 this.scrollArea = null; // 当前元素高度 this.scrollTop = null; // 滚动位置 this.$domHeight = 0; if (that.$dom[0].scrollHeight>that.$dom[0].clientHeight){ // 实际高度比可视高度大时 if (that.pageMax>1){ // 最大页码 > 1 that.$dom.append(that.$tips); // 提示上拉加载更多 } } // 判断$dom滚动 this.$dom.scroll(function(){ that.scrollArea = Math.floor(that.$dom[0].scrollHeight-that.$dom[0].clientHeight); // 元素实际高度 - 可视高度 that.scrollTop = Math.ceil(that.$dom[0].scrollTop); // 元素滚动位置 if (that.scrollArea===that.scrollTop) that.next(); // 判断 滚动位置 === 当前元素高度 调用 next() }) } loading (texts) { this.$tips.text(texts); // 改变加载提示 } // 加载 onload (html) { this.$tips.remove(); // 清除加载提示 this.$dom.append(html); // 把传过来的html插入dom this.$dom.append(this.$tips); // 插入加载提示 // 判断最大页码 , 初始页 if (this.pageNum===this.pageMax) this.$tips.text('没有更多啦~'); else this.$tips.text('上拉加载更多'); if (this.pageMax===1 && this.pageNum===1) this.$tips.remove(); } // 重置 reset ({ pageNum, pageMax, html }) { this.pageNum = pageNum // 重置当前页码为首页 this.pageMax = pageMax // 重置最大页码 // this.$dom.html('') // 清空原有列表数据 this.onload(html) // 重新加载首页数据 } // next() { console.log(this.pageNum) if (this.pageNum<this.pageMax) { // 判断初始页小于最大页码 this.pageNum++ // 初始页+1 this.onPage(this.pageNum) // 执行onPage() } } } </script> </body> </html>

 

posted @ 2020-04-21 14:36  sanyekui  阅读(422)  评论(0编辑  收藏  举报