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/border | jQuery 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 模式文件高度
最佳實踐建議
- 佈局計算用
outerWidth/Height(true) 取得真實佔用空間。
- 動畫/過渡中取值需注意重繪時機,可用
requestAnimationFrame。
- 響應式設計監聽
$(window).resize() 並防抖動重新計算。
- 大量元素測量時,考慮
getBoundingClientRect() 批次讀取避免強制回流。