監聽 window.scroll 事件,當滾動條距離頁面底部小於閾值時,觸發 AJAX 請求追加數據。
// 視口高度 + 滾動距離 >= 文檔高度 - 閾值
$(window).height() + $(window).scrollTop() >= $(document).height() - threshold
$(function() {
var $content = $("#content");
var page = 1;
var pageSize = 10;
var loading = false;
var threshold = 50; // 提前 50px 觸發
function loadMore() {
if (loading) return;
loading = true;
$content.append("加載中...");
$.getJSON("/api/items", { page: page, size: pageSize })
.done(function(data) {
$(".loading").remove();
if (data.length === 0) {
$content.append("已無更多數據");
$(window).off("scroll", scrollHandler); // 解除綁定
return;
}
// 渲染數據
var html = data.map(function(item) {
return "" + item.title + "";
}).join("");
$content.append(html);
page++;
loading = false;
})
.fail(function() {
$(".loading").remove();
$content.append("加載失敗,請重試");
loading = false;
});
}
function scrollHandler() {
var scrollTop = $(window).scrollTop();
var docHeight = $(document).height();
var winHeight = $(window).height();
if (winHeight + scrollTop >= docHeight - threshold) {
loadMore();
}
}
$(window).on("scroll", scrollHandler);
// 初始加載第一頁
loadMore();
});
_.throttle 或 requestAnimationFrame 限制 scroll 事件頻率。var observer = new IntersectionObserver(function(entries) {
if (entries[0].isIntersecting) loadMore();
}, { rootMargin: '100px' });
observer.observe(document.querySelector('.load-trigger'));
loading 標誌位 + 移除觸發元素觀察。$(document).height() 不準,應監聽容器 scroll 而非 window。onload 後重新計算或預留高度。resize 重算。