实现原理
当前滚动条的位置 + 当前可视范围的高度 = 文档的高度
实现方法
<div class="new-list_">
<ul id="thelist"> </ul>
<p class="refreshText">加载中...</p>
</div>
<img src="images/top.png" class="top-img" alt="">
$(document).ready(function () {
let pageIndex = 1;
getlist()
$('.top-img').click(() => {
$('html,body').animate({
scrollTop: 0
}, 500);
});
// 获取当前滚动条的位置
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);
}
$(window).scroll(function () {
// 回到顶部按钮展示判断
if ($(window).scrollTop() >= 200) {
$('.top-img').fadeIn();
} else {
$('.top-img').fadeOut();
}
if (getScrollTop() + getClientHeight() == getScrollHeight()) {
$('.refreshText').css('display', 'block')
setTimeout(() => {
pageIndex++
getlist()
console.log('上拉')
}, 500);
}
});
// 获取列表数据并动态插入数据
function getlist() {
let url2 = 'https://www.xxx.com'
$.get(url2, function (res) {
let obj2 = JSON.parse(res).data
const list2 = []
Object.keys(obj2).forEach(function (item, index) {
this.push(obj2[item])
}, list2)
for (var i = 0; i < list2.length; i++) {
$("#thelist").append(
`<li>
<div class="li-item">
<img src="${list2[i].imageInfo.imageList[0].url}">
<div class="new-list_right">
<div class="favor" οnclick="doFavor('${list2[i].imageInfo.imageList[0].url}','${list2[i].skuName}','${list2[i].couponInfo.couponList[0]?list2[i].couponInfo.couponList[0].discount:''}','${list2[i].priceInfo.price}','${list2[i].couponInfo.couponList[0]?list2[i].couponInfo.couponList[0].link:''}','${list2[i].skuId}','${list2[i].materialUrl}')">推荐</div>
<div class="new-name ${list2[i].couponInfo.couponList[0]?'':'set-margin'}"><span><img class="jd" src="images/jd.png"></span>${list2[i].skuName}</div>
<div class="new-quan ${list2[i].couponInfo.couponList[0]?'':'hide'} ">
<span>券</span>
<div>¥${list2[i].couponInfo.couponList[0]?list2[i].couponInfo.couponList[0].discount: '0'}</div>
</div>
<span class="new-price">¥${list2[i].priceInfo.price}</span>
</div>
</div>
</li>`
)
}
});
}
});