監聽 $(window).scroll() 事件,計算捲動位置與視窗高度、文件總高度的關係。當捲動到底部附近(預設 50px 緩衝)時,觸發 AJAX 載入下一頁資料。
| 屬性 | 意義 | 變化時機 |
|---|---|---|
$(window).height() | 瀏覽器可視區域高度 | 視窗縮放時改變 |
$(document).height() | 整份文件總高度 | 內容動態新增時改變 |
$(window).scrollTop() | 目前捲動距離(視窗頂端到文件頂端) | 捲動時改變 |
var bot = 50; // 緩衝距離
if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
// 觸發載入
}
$(document).ready(function() {
var loading = false; // 防止重複請求
var page = 1;
$(window).scroll(function() {
if (loading) return;
var bot = 50;
if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
loading = true;
page++;
$.getJSON('/api/articles', { page: page }, function(data) {
if (data.length === 0) {
$('#loadMore').text('已無更多內容').show();
$(window).off('scroll'); // 移除事件
return;
}
// 追加內容到容器
data.forEach(function(item) {
$('#contentList').append('' + item.title + '');
});
loading = false;
}).fail(function() {
loading = false;
alert('載入失敗');
});
}
});
});
IntersectionObserver API 替代 scroll 事件,效能更佳、不阻塞主執行緒。setTimeout 或 requestAnimationFrame 降低檢查頻率。// 取得捲動距離
$(document).scrollTop(); // 垂直
$(document).scrollLeft(); // 水平
// 判斷頂端/底端
$(document).scrollTop() === 0; // 頂端
$(document).scrollTop() >= $(document).height() - $(window).height(); // 底端
// 即時顯示捲動位置(除錯用)
$(document).scroll(function() {
$('#debug').text($(document).scrollTop());
});
<span id="debug" style="position:fixed; top:10px; left:10px; background:rgba(0,0,0,0.7); color:#fff; padding:5px;"></span>