前端无限上拉加载实现总结

在移动端的开发中,常常碰到上拉无限加载的需求。在此作个总结供你们分享。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')

好啦,就总结到这了

相关文章
相关标签/搜索