萬盛學電腦網

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

jQuery height() 系列方法獲取各種高度完整速查表

jQuery 高度方法對照表

方法回傳值包含內容適用對象
.height()內容高度內容區 (不含 padding/border/margin)元素、window、document
.innerHeight()內部高度內容 + padding元素
.outerHeight()外部高度內容 + padding + border元素
.outerHeight(true)完整外部高度內容 + padding + border + margin元素

window / document 特殊行為

呼叫方式意義等同原生
$(window).height()瀏覽器視窗可視區高度 (viewport)window.innerHeight
$(window).width()瀏覽器視窗可視區寬度window.innerWidth
$(document).height()文件總高度 (含溢出)document.documentElement.scrollHeight
$(document).width()文件總寬度document.documentElement.scrollWidth
$(document.body).height()body 元素高度document.body.scrollHeight (視模式)
$(document.body).outerHeight(true)body 完整高度 (含 margin)—

實用代碼片段

<script>
$(function() {
  // 視窗可視區
  console.log('Viewport:', $(window).width(), 'x', $(window).height());
  
  // 文件總尺寸
  console.log('Document:', $(document).width(), 'x', $(document).height());
  
  // Body 尺寸
  console.log('Body:', $(document.body).width(), 'x', $(document.body).height());
  console.log('Body (with margin):', $(document.body).outerWidth(true), 'x', $(document.body).outerHeight(true));
  
  // 元素完整尺寸 (含 margin)
  var $box = $('#box');
  console.log('Box 完整尺寸:', $box.outerWidth(true), 'x', $box.outerHeight(true));
  
  // 置中計算 (需 outerWidth/outerHeight)
  function centerElement($el) {
    $el.css({
      position: 'absolute',
      left: ($(window).width() - $el.outerWidth()) / 2 + $(window).scrollLeft(),
      top: ($(window).height() - $el.outerHeight()) / 2 + $(window).scrollTop()
    });
  }
});
</script>

常見陷阱與解決

問題原因解決
height() 回傳 0元素隱藏 (display:none) 或未渲染確保元素可見後再取值,或用 clone().css({visibility:'hidden',display:'block'}).appendTo(body) 離屏測量
window/document 高度不準CSS 未載入完成、圖片未載入撐開高度在 $(window).on('load', fn) 或圖片 onload 後取值
fixed 定位元素高度計算錯誤脫離文件流,不計入 document.height單獨計算 fixed 元素高度
box-sizing: border-box 影響width/height 包含 padding/borderjQuery height() 始終回傳 content-box 高度,outerHeight() 含 border-box

原生 JS 對應屬性速查

// 元素
el.clientHeight      // = $().height() + padding (無 border)
el.offsetHeight      // = $().outerHeight() (含 border)
el.scrollHeight      // 實際內容高度 (含溢出)

// 視窗
window.innerHeight   // = $(window).height()
document.documentElement.clientHeight // 標準模式視窗高度

// 文件
document.documentElement.scrollHeight // = $(document).height()
document.body.scrollHeight            // Quirks 模式文件高度

最佳實踐建議

  1. 佈局計算用 outerWidth/Height(true) 取得真實佔用空間。
  2. 動畫/過渡中取值需注意重繪時機,可用 requestAnimationFrame。
  3. 響應式設計監聽 $(window).resize() 並防抖動重新計算。
  4. 大量元素測量時,考慮 getBoundingClientRect() 批次讀取避免強制回流。
copyright © 萬盛學電腦網 all rights reserved