jquery上拉加载
jQuery 上拉加载实现方法
上拉加载是一种常见的分页加载技术,当用户滚动到页面底部时自动加载更多内容。以下是几种实现方式:
基础滚动监听实现
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
loadMoreData();
}
});
function loadMoreData() {
// 防止重复加载
if (isLoading) return;
isLoading = true;
$.ajax({
url: 'your-api-url',
type: 'GET',
data: { page: nextPage },
success: function(response) {
// 追加新内容
$('#container').append(response.html);
nextPage++;
isLoading = false;
}
});
}
使用Intersection Observer API(现代浏览器)
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
loadMoreData();
}
}, {threshold: 0.1});
observer.observe($('#load-more-trigger')[0]);
优化版实现
var loading = false;
var lastPage = false;
$(window).scroll(function() {
if (!loading && !lastPage && $(window).scrollTop() > $(document).height() - $(window).height() - 200) {
loading = true;
$('#loading-indicator').show();
$.get('load-more.php', {page: nextPage})
.done(function(data) {
if (data.items.length === 0) {
lastPage = true;
$('#no-more-data').show();
} else {
$('#items-container').append(data.html);
nextPage++;
}
})
.always(function() {
loading = false;
$('#loading-indicator').hide();
});
}
});
插件推荐
-
jQuery Infinite Scroll
官方插件,简化实现过程:$('#container').infinitescroll({ navSelector: ".pagination", nextSelector: ".pagination a.next", itemSelector: ".item", loading: { msgText: "加载中...", finishedMsg: "没有更多内容了" } }); -
jScroll
轻量级插件:$('#content').jscroll({ loadingHtml: '<div class="loading">加载中...</div>', padding: 20, nextSelector: 'a.next:last' });
注意事项
- 添加防抖机制避免频繁触发
- 显示加载状态和没有更多数据的提示
- 服务端需要支持分页查询
- 移动端需要考虑触摸事件
- 禁用加载时锁定滚动事件
完整示例通常包含:
- 滚动位置计算
- AJAX请求发送
- 新内容追加
- 状态管理(加载中/结束)
- 错误处理





