關鍵尺寸屬性
| 屬性 | 意義 |
$(document).height() | 文件總高度 |
$(window).height() | 視窗可視區高度 |
$(document).scrollTop() | 垂直捲動距離 (視窗頂到文件頂) |
$(document).scrollLeft() | 水平捲動距離 |
判斷邏輯
// 到達頂部
$(document).scrollTop() === 0
// 到達底部 (或接近底部)
var scrollTop = $(document).scrollTop();
var windowHeight = $(window).height();
var docHeight = $(document).height();
// 精確到底部
scrollTop + windowHeight >= docHeight
// 或預留緩衝 (如 100px 提前觸發)
var buffer = 100;
scrollTop + windowHeight >= docHeight - buffer
完整監聽範例
$(document).ready(function() {
// 即時顯示捲動位置 (除錯用)
$(document).scroll(function() {
$('#debug').text('scrollTop: ' + $(document).scrollTop());
});
// 底部載入更多
var loading = false;
$(window).scroll(function() {
if (loading) return;
var scrollTop = $(document).scrollTop();
var windowHeight = $(window).height();
var docHeight = $(document).height();
if (scrollTop + windowHeight >= docHeight - 100) { // 距底 100px 觸發
loading = true;
$('#loading').show();
$.getJSON('/api/more', { page: nextPage }, function(data) {
if (data.items.length === 0) {
$('#nomore').show();
$(window).off('scroll'); // 移除監聽
return;
}
data.items.forEach(function(item) {
$('#list').append('' + item.title + '
');
});
nextPage++;
loading = false;
$('#loading').hide();
});
});
});
});
<!-- 除錯顯示 -->
<span id="debug" style="position:fixed; top:10px; right:10px; background:rgba(0,0,0,0.7); color:#fff; padding:5px; z-index:9999;"></span>
<div id="loading" style="display:none; text-align:center; padding:10px;">載入中...</div>
<div id="nomore" style="display:none; text-align:center; padding:10px; color:#999;">已無更多內容</div>
效能優化建議
- 節流:
scroll 事件高頻觸發,使用 setTimeout 或 requestAnimationFrame 節流,或引用 lodash.throttle/underscore.throttle。
- IntersectionObserver:現代替代方案,瀏覽器原生支援,無需計算座標,效能極佳。
// IntersectionObserver 範例 (底部哨兵元素)
var observer = new IntersectionObserver(function(entries) {
if (entries[0].isIntersecting) {
loadMore();
}
}, { rootMargin: '100px' }); // 提前 100px 觸發
observer.observe(document.getElementById('sentinel')); // 放在列表最後的空 div
水平捲動判斷
// 到達最左
$(document).scrollLeft() === 0
// 到達最右
$(document).scrollLeft() + $(window).width() >= $(document).width()