工学1号馆

home

基于thinkphp的下拉加载更多功能的实现

Wu Yudong    February 26, 2021     ThinkPHP   908   

最近项目中需要实现下拉加载更多功能,本文记录一下自己的实现过程

首先是前端,需要判断鼠标滑动的位置和当前窗口的大小的判断,兼容移动端和PC端

//获取滚动条当前的位置
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);
}

实现了各种兼容的高度获取函数以后,就是进行一个判断即可:

if (getScrollTop() + getClientHeight() >= getScrollHeight()) {
    page++;
    get_more_article();
}

这里的get_more_article()实现的是当鼠标滑动到浏览器底部的时候进行无刷新加载,自然需要ajax来实现:

//ajax获取数据
function get_more_article() {
    $.ajax({
        type: 'POST',
        url: '{:url("home/article/get_more_article")}',
        dataType: 'json',
        data: {'page':page, .....},
        success: function (res) {
        if (res.err_no === 0) {
            //将返回值动态加载,动态生成标签。
            var html = "";
            for (i = 0; i < res.data.length; i++) {
                html += '<li class="item">';
                html += '........';
            }
            $("#entry-list").append(html);
        }
    },
    error: function (XMLHttpRequest, textStatus, errorThown) {
        alert("加载失败!");
    }
    });
}

至于后端的代码比我预期的要简单得多,这得益于tp的强大分页机制:

public function get_more_article(){
    $param = $this->request->param();
    $article_list = ArticleModel::where(....)->order(...)->page($param['page'], 10)->select()->toArray();
    if(!empty($article_list)) {
        $sldata['err_no'] = 0;
        $sldata['err_msg'] = 'success';
        $sldata['data'] = $article_list;
    } else {
        $sldata['err_no'] = 1;
        $sldata['err_msg'] = 'fail';
    }
    return json($sldata);
}

好了,到此为止整个功能已经实现,PC以及移动端都可以运行

如果文章对您有帮助,欢迎点击下方按钮打赏作者

Comments

No comments yet.
To verify that you are human, please fill in "七"(required)