- 方式一
使用 jroll.js 实现无限滚动,具体使用方式见
demo地址
官方地址
优点:封装好了加载方式,需要配合jroll-infinite.js插件,优化了超长列表滚动,img图片的可视区域显示,
缺点:滑动基于transform ,无法实现ios点击状态栏回到顶部,滑动时会出现卡顿和不流畅等情况。
- 方式二
基于 scroll 事件 判断滚动距离和屏幕高度是否到达底部,再出发加载,结合art-template模版引擎渲染列表。
简单实现:(实际实现的更为复杂判断的情况更多)
function ajax(parms) {
var a = [],
i;
var page = parms.url.replace("getData.do?page=", "");
for (i = 1; i <= 20; i++) {
a.push({
"index": i + (page - 1) * 20,
"text": "普通分页加载" + i + (page - 1) * 20
});
}
setTimeout(function () {
parms.success({
success: true,
msg: a
});
}, 800);
}
var infiniteLoad = {
page: 0,
timers: null,
lock: false,
init() {
this.page = 0;
this.timers = null;
this.LoadingDataFn();
const resize = this.resize
window.addEventListener('scroll', this.debounce(resize, 300))
window.addEventListener('resize', this.debounce(resize, 300))
window.addEventListener('orientationchange', this.debounce(resize, 300))
},
debounce(fn, delay) {
let time;
return function () {
let that = this,
args = arguments;
if (time) clearTimeout(time);
setTimeout(function () {
fn.apply(that, args)
}, delay)
}
},
resize() {
let that = infiniteLoad
if (($(window).height() + $(window).scrollTop() + 60) >= $(document).height() && !that.lock) {
that.page++;
that.LoadingDataFn();
}
},
LoadingDataFn() {
let that = this
that.showloading();
that.lock = true
console.log("第" + that.page + "页");
ajax({
type: "GET",
url: "getData.do?page=" + this.page,
data: {
'page': this.page,
},
dataType: "json",
success: function (data) {
if (data.success) {
that.hideloading();
var html = template('data-tpl', data);
$(".numList").append(html);
} else {
that.showhiding();
}
that.lock = false
}
});
},
showloading() {
$(".loading").show()
// document.querySelector('.loading').style.display = 'block'
},
hideloading() {
$(".loading").hide()
// document.querySelector('.loading').style.display = 'none'
},
showhiding() {
$(".ending").show().delay(1500).hide(0);
// let time;
// document.querySelector('.loading').style.display = 'block'
// if(time){clearTimeout(time)}
// timesetTimeout(function() {
// document.querySelector('.loading').style.display = 'none'
// },1500)
}
}
//初始化, 第一次加载
// $(document).ready(function () {
// infiniteLoad.init()
// });
document.addEventListener('DOMContentLoaded',function(){
infiniteLoad.init()
});
优点:模版更自由使用,可以触发点击状态栏返回顶部,资源不多的情况下滑动更流畅。
缺点:数据大的情况下卡顿。
后期可以待改进,进一步封装,去除jquery,等有时间我会进一步完善。