首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

jQuery $(document).height() vs $(window).height() 差異徹底解析

     編輯:程式設計疑難解答

定義對照

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(近似值,實際受邊框、邊距影響)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved