方法速查
| 方法 | 獲取 | 設置 | 影響範圍 | 包含內容 |
.width() |
✅ 內容區寬度 |
✅ 設置內容區寬度 |
單個元素 |
僅 content(不含 padding/border/margin) |
.height() |
✅ 內容區高度 |
✅ 設置內容區高度 |
單個元素 |
僅 content |
.innerWidth() |
✅ content + padding |
❌ 僅獲取 |
單個元素 |
content + padding |
.innerHeight() |
✅ content + padding |
❌ 僅獲取 |
單個元素 |
content + padding |
.outerWidth() |
✅ content + padding + border |
❌ 僅獲取 |
單個元素 |
+ margin(傳 true) |
.outerHeight() |
✅ content + padding + border |
❌ 僅獲取 |
單個元素 |
+ margin(傳 true) |
基礎範例:設置寬高
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 設置寬高</title>
<style>
#box {
width: 300px; height: 100px;
padding: 10px; margin: 3px;
border: 1px solid #3498db;
background: #ecf0f1;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="box">原始:300×100(含 padding/border 實際更大)</div>
<br>
<button id="btn-resize">設置為 500×500(內容區)</button>
<script>
$('#btn-resize').click(function() {
$('#box').width(500).height(500);
// 內容區變 500×500,外部尺寸 = 500 + padding*2 + border*2
});
</script>
</body>
</html>
關鍵行為細節
- 單位:數值視為像素,字串可帶單位
'50%'、'10em'、'auto'。
- 盒模型:設置的是 content-box 尺寸。若元素
box-sizing: border-box,實際渲染尺寸會不同,jQuery 仍按 content-box 計算。
- 隱藏元素:
display:none 元素獲取寬高為 0。需先 .show() 或臨時 .css({position:'absolute', visibility:'hidden', display:'block'}) 測量。
- 鏈式調用:返回 jQuery 物件,可
.width(100).height(200).css('color','red')。
- 多元素設置:
$('.items').width(200) 為所有匹配元素設置相同寬度。
進階:響應式動態計算
// 等寬列:容器寬度 / 列數 - 間距
function equalizeColumns($container, colCount, gap = 10) {
const containerWidth = $container.innerWidth(); // 含 padding
const itemWidth = (containerWidth - gap * (colCount - 1)) / colCount;
$container.children().width(itemWidth);
}
$(window).on('resize', debounce(() => equalizeColumns($('#grid'), 4), 100));
常見坑點
| 現象 | 原因 | 解決 |
| 設置寬高無效果 |
元素 display:inline 或 static 定位無尺寸 |
設置 display:inline-block/block/flex 或 position:relative/absolute |
| 獲取寬高為 0 |
元素或祖先 display:none |
臨時顯示測量或用 getBoundingClientRect() |
| 百分比設置異常 |
父元素無明確寬高 |
確保父元素有確定尺寸,或用 calc() / Flex/Grid 佈局 |
| box-sizing 導致視覺不符 |
jQuery 操作 content-box,CSS 渲染 border-box |
統一用 box-sizing:border-box 並用 .outerWidth(true) 計算,或改用 CSS 變量控制 |
現代替代:CSS 變量 + 原生 API
/* CSS */
:root { --box-size: 300px; }
.box { width: var(--box-size); height: var(--box-size); }
/* JS */
box.style.setProperty('--box-size', '500px'); // 一次性更新所有引用該變量的元素
// 或
box.style.width = '500px'; // 直接操作 style
// 獲取
const w = box.clientWidth; // content + padding
const w2 = box.getBoundingClientRect().width; // 含 border,精確到小數
總結
- 設置內容區尺寸:
.width(val) / .height(val)。
- 獲取含 padding/border/margin 尺寸:
.innerWidth()/.outerWidth(true)。
- 注意 box-sizing 差異:jQuery 操作 content-box,CSS 渲染可能 border-box。
- 隱藏元素無法測量:需顯示後或用原生
getBoundingClientRect()。
- 現代項目優先 CSS 變量/ Flex/Grid,減少 JS 尺寸計算,提升性能與可維護性。