jQuery 尺寸位置 API 看似簡單,實戰中極易混淆:**`outerHeight(true)` vs `outerHeight()`**、**`position()` vs `offset()`**、**`scrollTop()` 到底量誰的高**。本文用**假想屏幕向上延伸模型**徹底釐清,附手繪圖解與代碼驗證邏輯。
以高度為例,寬度邏輯同理:
innerHeight() = padding-top + height + padding-bottom
outerHeight() = outerHeight(false)
= border-top + padding-top + height + padding-bottom + border-bottom
outerHeight(true)
= margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom

**易錯點**:`outerHeight()` 默認參數為 `false`(不含 margin),極易記反。
**核心區別只有一個:參考系不同**
| API | 參考系 | 適用場景 |
|---|---|---|
| `offset()` | **文檔** | 全局定位、彈窗居中、元素相對頁面座標 |
| `position()` | **最近的有定位父級** | 相對父容器定位、拖拽限制區域、局部佈局計算 |
無定位父級時,`position()` 退化為相對文檔,與 `offset()` 相同——**但代碼中必須明確語義,避免維護陷阱**。
很多初學者不理解 `$(document).scrollTop()`。引入**假想屏幕向上延伸**概念:

圖中綠色區域即 `scrollTop()` 代表的長度——一眼看懂,永不忘記。
<div id="outer" style="margin:20px; border:5px solid red; padding:10px; width:300px; height:200px; overflow:auto;">
<div id="inner" style="height:500px; background:linear-gradient(blue, green);"></div>
</div>
<script>
const $outer = $('#outer');
const $inner = $('#inner');
console.log('=== 尺寸 ===');
console.log('inner height:', $inner.innerHeight()); // 500
console.log('outer height:', $outer.innerHeight()); // 200 (可視區高度)
console.log('outer height(true):', $outer.outerHeight(true)); // 200+20+20+5+5=250
console.log('=== 位置 ===');
console.log('inner offset:', $inner.offset()); // {top: 35, left: 35} 相對文檔
console.log('inner position:', $inner.position()); // {top: 15, left: 15} 相對 #outer (有 relative 定位)
console.log('=== 滾動 ===');
$outer.scrollTop(100);
console.log('outer scrollTop:', $outer.scrollTop()); // 100
console.log('inner position after scroll:', $inner.position()); // {top: -85, left: 15} 相對父級可視區
</script>
尺寸與位置 API 是前端佈局、動畫、拖拽、虛擬列表的基石。**圖解建立心智模型,代碼驗證鞏固肌肉記憶**——收藏本文,下次遇到「為什麼位置對不上」時,30 秒定位根因。