萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 獲取 document 與 window 尺寸:.width()/.height() 在文檔與視口上的應用

核心概念區分

對象代表含義典型用途
$(window) 瀏覽器視口(可見區域),不含瀏覽器工具欄、滾動條 響應式斷點判斷、滾動監聽、懶加載觸發、模態框定位
$(document) 整個文檔(含超出視口需滾動的部分) 頁面總高度、滾動進度計算、無限滾動觸發點
screen 用戶螢幕物理分辨率 全屏適配、多螢幕檢測、PWA 安裝提示

基礎範例:點擊顯示尺寸

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>document vs window 尺寸</title>
  <style> body { height: 3000px; } </style> /* 強制產生滾動 */
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <button id="btn-dim">顯示 document 與 window 尺寸</button>

  <script>
    $('#btn-dim').click(function() {
      const docW = $(document).width();
      const docH = $(document).height();
      const winW = $(window).width();
      const winH = $(window).height();
      
      alert(`Document: ${docW} × ${docH}\nWindow: ${winW} × ${winH}`);
      // 輸出示例:Document: 1920 × 3000, Window: 1920 × 937
    });
  </script>
</body>
</html>

關鍵屬性對照表(jQuery vs 原生)

需求jQuery原生(推薦現代項目)
視口寬度 $(window).width() window.innerWidth / document.documentElement.clientWidth
視口高度 $(window).height() window.innerHeight / document.documentElement.clientHeight
文檔寬度 $(document).width() document.documentElement.scrollWidth
文檔高度 $(document).height() document.documentElement.scrollHeight
滾動左偏移 $(window).scrollLeft() window.scrollX / document.documentElement.scrollLeft
滾動上偏移 $(window).scrollTop() window.scrollY / document.documentElement.scrollTop

實戰場景與代碼模式

1. 響應式斷點判斷


const isMobile = () => $(window).width() < 768;
// 或現代:window.matchMedia('(max-width: 767px)').matches

2. 滾動進度百分比


$(window).on('scroll', function() {
  const scrollTop = $(this).scrollTop();
  const docH = $(document).height();
  const winH = $(this).height();
  const progress = scrollTop / (docH - winH) * 100;
  $('#progress-bar').css('width', progress + '%');
});

3. 無限滾動觸發


$(window).on('scroll', debounce(function() {
  if ($(window).scrollTop() + $(window).height() >= $(document).height() - 200) {
    loadMore();
  }
}, 100));

4. 模態框垂直居中(動態計算)


function centerModal($modal) {
  const winH = $(window).height();
  const modalH = $modal.outerHeight();
  $modal.css('top', Math.max(0, (winH - modalH) / 2) + 'px');
}
$(window).on('resize', () => centerModal($('#modal')));

5. 元素是否在視口內


function isInViewport($el) {
  const rect = $el[0].getBoundingClientRect();
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= $(window).height() &&
    rect.right <= $(window).width()
  );
}
// 或現代 IntersectionObserver API(性能更優)

常見坑點

  • 文檔高度變化未更新:AJAX 載入內容後 $(document).height() 需重新讀取,或監聽 DOMSubtreeModified(已棄用)改用 MutationObserver。
  • 移動端視口單位陷阱:iOS Safari 地址欄隱藏/顯示導致 vh 變化,$(window).height() 實時反映可見高度,CSS 100vh 可能超出實際可見區。
  • 縮放頁面時尺寸異常:用戶縮放頁面時 innerWidth 含縮放比,clientWidth 不含。按需選擇。
  • iframe 內獲取父頁面尺寸:parent.$(window).width()(同域下)。

性能建議

  • 高頻事件(scroll/resize)必須 防抖/節流(lodash.debounce、requestAnimationFrame)。
  • 批量讀取佈局屬性會觸發強制同步佈局,盡量「讀寫分離」或用 getBoundingClientRect() 一次性讀取。
  • 現代項目優先原生 API(window.innerWidth、IntersectionObserver、ResizeObserver),無 jQuery 依賴、性能更優。

總結

$(window) 對應視口,$(document) 對應完整文檔。掌握兩者尺寸獲取與滾動座標體系,是實現響應式、無限滾動、懶加載、模態框定位、滾動進度條等核心交互的基石。現代開發建議逐步遷移至原生 API,僅在維護舊代碼或需 jQuery 兼容層時使用。

copyright © 萬盛學電腦網 all rights reserved