前端無限上拉加載實現總結

在移動端的開發中,常常碰到上拉無限加載的需求。在此作個總結供你們分享。html

1.什麼時候觸發加載?瀏覽器

一般,咱們滑動到頁面底部沒有內容時,須要觸發加載app

先來普及一些屬性dom

 $(window).scrollTop()爲滾動條在Y軸上的滾動距離。this

$(window).height()爲內容可視區域的高度。url

$(document).height()爲內容可視區域的高度加上溢出(滾動)的距離。插件

因此,當 $(window).scrollTop()+$(window).height()==$(document).height()時便可斷定用戶已經滑動到底部,該是時機觸發加載新內容了。htm

2.實現對象

var doing = $.pageLoader({length: 5, url: "doing", tpl: "projectTpl", dom: "#doing"});
$(window).scroll(function () {
    if ((($(window).scrollTop() + $(window).height())) >= $(document).height()) {
            if (!doing.onLoading && !doing.isLast) {
                doing.index++;
                doing.load();
            }
    }
});

其中的doing對象是我簡單封裝的一個插件開發

/**
 * 分頁加載數據插件
 * @param opts
 * @returns {{init: Function, load: Function, isLast: boolean, onloading: boolean}}
 */
$.pageLoader = function (opts) {
    var defaultOpts = {index: 0, length: 10};

    var opts = $.extend({}, defaultOpts, opts);

    var appendData = function (result, _this) {
        var html = template(opts.tpl, {data: result.content});
        $(opts.dom).append(html);
        _this.isLast = result.last;
        _this.onLoading = false;
    }

    return {
        init: function () {
            this.load();
            return this;
        },
        load: function () {
            var _this = this;
            _this.onLoading = true;
            $.get(opts.url, {page: _this.index, size: opts.length}, function (result) {
                appendData(result, _this);
            });
            return this;
        },
        isLast: false,
        onloading: false,
        index:opts.index

    }.init();
}

3.頁面中某個元素實現無限滾動

以上實現是基於window的滾動,也就是整個頁面進行無限上拉加載。但一般咱們的頁面總有一些元素是須要固定顯示在頂部。好比下圖咱們在頁面頂部須要顯示切換按鈕

此時,咱們一般會將列表顯示部分設置爲絕對定位,而後設置距離頂部和底部的距離。

將overflow設置爲auto,

若是內容被修剪,則瀏覽器會顯示滾動條以便查看其他的內容。

也能夠設置爲scroll

內容會被修剪,可是瀏覽器會顯示滾動條以便查看其他的內容。

判斷是否到底部原理同上,已滾動距離+滾動區域可視高度==滾動區域高度

$("dom").scrollTop() + ($(window).height() - $('.header').height()) >= $('dom').prop('scrollHeight')

好啦,就總結到這了

相關文章
相關標籤/搜索