移动端无限滚动加载分页实现
一、实现原理
通过监听页面滚动事件,当滚动条触底时触发下一页内容加载。
关键概念
- scrollHeight:元素内容的总高度
- clientHeight:可见区域高度
- scrollTop:滚动条偏移量
实现思路
- 使用固定定位加载容器
- 监听页面滚动事件
- 通过高度差判断是否触底加载
二、代码实现
方案一:基础实现
<script>
let currentPage = 2;
let totalPages;
const categoryId = '6';
function loadContent() {
$.ajax({
url: '/ajax.php',
method: 'POST',
data: { page: currentPage, category: categoryId },
success: (response) => {
appendItems(response.items);
}
});
}
function appendItems(items) {
const container = $('.item-list');
const markup = items.map(item =>
`<li><a href="${item.url}">${item.title}</a></li>`
).join('');
container.append(markup);
currentPage++;
}
function handleScroll() {
const docHeight = document.documentElement.scrollHeight;
const winHeight = window.innerHeight;
const scrollPos = window.pageYOffset;
if (docHeight - winHeight - scrollPos < 50) {
loadContent();
}
}
$(window).scroll(handleScroll);
</script>
方案二:优化实现
<script>
const categoryId = '6';
let currentPage = 2;
const contentUrl = '/ajax-content.php';
$(window).scroll(function() {
const winHeight = window.innerHeight || $(window).height();
const isNearBottom = $(window).scrollTop() + winHeight > $(document).height() - 50;
if (!isNearBottom) return;
if (parseInt($('.page-num').last().text()) >= currentPage) return;
$.post(contentUrl, { category: categoryId, page: currentPage }, function(response) {
appendContent(response);
currentPage++;
}, 'json');
});
function appendContent(data) {
const container = $('.content-container');
const items = data.map(item =>
`<div class="item">${item.title}</div>`
).join('');
container.append(items);
}
</script>
方案三:插件实现
基于iScroll的下拉刷新和上拉加载插件
特点:
- 支持下拉刷新
- 支持上拉加载
- 自动判断内容高度
- 适合移动端优化