定義對照
| API | 含義 | 典型值 |
$(document).height() | 文件內容總高度(含捲動隱藏部分) | ≥ 視窗高度 |
$(window).height() | 瀏覽器視窗可視區域高度(Viewport) | 螢幕高度 - 瀏覽器介面 |
| 差值 | 垂直捲動軸最大捲動距離 | $(document).height() - $(window).height() |
為何首頁兩者相等?
- 內容高度 小於等於 視窗高度 → 無捲動軸
- CSS 設定
html, body { height: 100%; overflow: hidden; }
- 單頁應用 (SPA) 動態載入內容,測量時機過早(DOM 未就緒)
正確測量時機
// 等待圖片/字型載入完成
$(window).on('load', function() {
console.log('Doc:', $(document).height(), 'Win:', $(window).height());
});
// 或使用 ResizeObserver (現代瀏覽器)
new ResizeObserver(() => {
console.log($(document).height(), $(window).height());
}).observe(document.body);
實用場景
- 無限捲動:
$(window).scrollTop() + $(window).height() >= $(document).height() - 50
- 固定底部 Footer:內容高度 < 視窗高度時固定底部
- 彈窗垂直置中:
top = ($(window).height() - modal.outerHeight()) / 2 + $(window).scrollTop()
常見誤區
「$(window).height() 是捲動條高度」錯誤。捲動條高度 = document.height - window.height(近似值,實際受邊框、邊距影響)。