jQuery 尺寸
核对 CSS 盒模型各层跨度,以及 jQuery width/height、innerWidth/innerHeight、outerWidth/outerHeight 与外边距/border-box 实测尺寸。
学完这一章,你能够
- 核对 CSS 盒模型各层跨度,以及 jQuery width/height、innerWidth/innerHeight、outerWidth/outerHeight 与外边距/border-box 实测尺寸。
jQuery 六大尺寸方法与盒模型层级
jQuery 提供了一组专门用于读取和调整元素及浏览器窗口几何尺寸的方法,核心包含三对共六个接口:`width()`、`height()`、`innerWidth()`、`innerHeight()`、`outerWidth()` 与 `outerHeight()`。
对应 CSS 盒模型从内到外的四层结构(Element 内容区、Padding 内边距、Border 边框、Margin 外边距):`width()`/`height()` 仅度量最内层内容区;`innerWidth()`/`innerHeight()` 在内容区基础上计入内边距;`outerWidth()`/`outerHeight()` 再计入边框宽度;传入 `true`(`outerWidth(true)`/`outerHeight(true)`)时则进一步涵盖外边距(来源 488×340 盒模型尺寸图已完成像素核查并仅留存私有证据)。
内容区尺寸:width() 与 height()
`width()` 与 `height()` 设置或返回元素纯内容区的宽度和高度,不包含内边距、边框与外边距。本站离线 Chromium 构造标准盒模型(`box-sizing: content-box`)的 `#div1`(`width: 300px; height: 100px; padding: 10px; border: 1px solid blue; margin: 3px`),点击按钮实测 `$('#div1').width()` 返回 `300`、`$('#div1').height()` 返回 `100`,并将 `'div 的宽度是: 300<br>div 的高度是: 100'` 写回元素。
含内边距与含边框/外边距:inner* 与 outer*
`innerWidth()` 与 `innerHeight()` 返回元素内容区加上左右/上下内边距后的尺寸。对上述 `#div1`(四边 `padding: 10px`),本站实测 `innerWidth()` 为 `320`(`300 + 10×2`),`innerHeight()` 为 `120`(`100 + 10×2`)。
`outerWidth()` 与 `outerHeight()` 默认返回内容区加内边距再加边框后的尺寸,传入 `true` 时再叠加外边距。对同一 `#div1`(四边 `border: 1px`、`margin: 3px`),本站实测 `outerWidth()` 为 `322`、`outerHeight()` 为 `122`,而 `outerWidth(true)` 为 `328`、`outerHeight(true)` 为 `128`。进一步对比 `box-sizing: border-box` 的 `#div2`(声明宽 `300px`、高 `100px`、`padding: 10px`、`border: 1px`、`margin: 5px`),实测 `.width()` 仍返回纯内容宽 `278`、`.innerWidth()` 为 `298`、`.outerWidth()` 为 `300`、`.outerWidth(true)` 为 `310`;此外,调用 `$('#div1').width(400).height(150)` 可动态更新 `#div1` 至 `outerWidth() == 422`,`$(window).width()` 与 `$(window).height()` 也准确测得当前视口 `1200 × 800`。
离线 Chromium 实测 CSS 盒模型六大尺寸方法、border-box 差异与视口尺寸
"""Offline Playwright Chromium lab for jQuery Chapter 20 (dimensions)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<style>
body { margin: 0; font-family: sans-serif; }
#div1 {
box-sizing: content-box;
width: 300px;
height: 100px;
padding: 10px;
margin: 3px;
border: 1px solid blue;
background-color: lightblue;
}
#div2 {
box-sizing: border-box;
width: 300px;
height: 100px;
padding: 10px;
margin: 5px;
border: 1px solid green;
background-color: #d1e7dd;
}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<button id="btn-wh" type="button">显示宽高</button>
<script>
(function () {
function num(v) {
const n = parseFloat(v);
return Number.isNaN(n) ? 0 : n;
}
function JQ(els) {
this.els = Array.from(els);
this.length = this.els.length;
}
JQ.prototype.click = function (fn) {
this.els.forEach((el) => el.addEventListener('click', fn));
return this;
};
JQ.prototype.html = function (val) {
if (val === undefined) return this.els[0] ? this.els[0].innerHTML : undefined;
this.els.forEach((el) => { el.innerHTML = String(val); });
return this;
};
JQ.prototype.width = function (val) {
if (val === undefined) {
const el = this.els[0];
if (!el) return undefined;
if (el === window) return window.innerWidth;
if (el === document) return document.documentElement.scrollWidth;
const rect = el.getBoundingClientRect();
const cs = getComputedStyle(el);
return Math.round(rect.width - num(cs.paddingLeft) - num(cs.paddingRight) - num(cs.borderLeftWidth) - num(cs.borderRightWidth));
}
const px = typeof val === 'number' ? val + 'px' : String(val);
this.els.forEach((el) => {
const cs = getComputedStyle(el);
if (cs.boxSizing === 'border-box' && typeof val === 'number') {
el.style.width = (val + num(cs.paddingLeft) + num(cs.paddingRight) + num(cs.borderLeftWidth) + num(cs.borderRightWidth)) + 'px';
} else {
el.style.width = px;
}
});
return this;
};
JQ.prototype.height = function (val) {
if (val === undefined) {
const el = this.els[0];
if (!el) return undefined;
if (el === window) return window.innerHeight;
if (el === document) return document.documentElement.scrollHeight;
const rect = el.getBoundingClientRect();
const cs = getComputedStyle(el);
return Math.round(rect.height - num(cs.paddingTop) - num(cs.paddingBottom) - num(cs.borderTopWidth) - num(cs.borderBottomWidth));
}
const px = typeof val === 'number' ? val + 'px' : String(val);
this.els.forEach((el) => {
const cs = getComputedStyle(el);
if (cs.boxSizing === 'border-box' && typeof val === 'number') {
el.style.height = (val + num(cs.paddingTop) + num(cs.paddingBottom) + num(cs.borderTopWidth) + num(cs.borderBottomWidth)) + 'px';
} else {
el.style.height = px;
}
});
return this;
};
JQ.prototype.innerWidth = function () {
const el = this.els[0];
if (!el) return undefined;
const rect = el.getBoundingClientRect();
const cs = getComputedStyle(el);
return Math.round(rect.width - num(cs.borderLeftWidth) - num(cs.borderRightWidth));
};
JQ.prototype.innerHeight = function () {
const el = this.els[0];
if (!el) return undefined;
const rect = el.getBoundingClientRect();
const cs = getComputedStyle(el);
return Math.round(rect.height - num(cs.borderTopWidth) - num(cs.borderBottomWidth));
};
JQ.prototype.outerWidth = function (includeMargin) {
const el = this.els[0];
if (!el) return undefined;
const rect = el.getBoundingClientRect();
const cs = getComputedStyle(el);
const extra = includeMargin === true ? num(cs.marginLeft) + num(cs.marginRight) : 0;
return Math.round(rect.width + extra);
};
JQ.prototype.outerHeight = function (includeMargin) {
const el = this.els[0];
if (!el) return undefined;
const rect = el.getBoundingClientRect();
const cs = getComputedStyle(el);
const extra = includeMargin === true ? num(cs.marginTop) + num(cs.marginBottom) : 0;
return Math.round(rect.height + extra);
};
window.$ = function (sel) {
if (sel === window || sel === document) return new JQ([sel]);
return new JQ(document.querySelectorAll(sel));
};
$('#btn-wh').click(function () {
const txt = 'div 的宽度是: ' + $('#div1').width() + '<br>div 的高度是: ' + $('#div1').height();
$('#div1').html(txt);
});
})();
</script>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 1200, "height": 800})
page.set_content(HTML_DOC, wait_until="load")
# Case 1: width() and height() return content box only (excluding padding/border/margin)
page.click("#btn-wh")
c1 = page.evaluate("""() => ({
width: $('#div1').width(),
height: $('#div1').height(),
renderedHtml: $('#div1').html()
})""")
exp1 = {"width": 300, "height": 100, "renderedHtml": "div 的宽度是: 300<br>div 的高度是: 100"}
cases.append(dict(name="width_and_height_content_box", expected=exp1, actual=c1, passed=c1 == exp1))
# Case 2: innerWidth() and innerHeight() include padding (300+20=320, 100+20=120)
c2 = page.evaluate("({ innerWidth: $('#div1').innerWidth(), innerHeight: $('#div1').innerHeight() })")
exp2 = {"innerWidth": 320, "innerHeight": 120}
cases.append(dict(name="inner_width_and_height_with_padding", expected=exp2, actual=c2, passed=c2 == exp2))
# Case 3: outerWidth()/outerHeight() include padding+border, and (true) adds margin
c3 = page.evaluate("""() => ({
outerWidth: $('#div1').outerWidth(),
outerHeight: $('#div1').outerHeight(),
outerWidthWithMargin: $('#div1').outerWidth(true),
outerHeightWithMargin: $('#div1').outerHeight(true)
})""")
exp3 = {
"outerWidth": 322,
"outerHeight": 122,
"outerWidthWithMargin": 328,
"outerHeightWithMargin": 128,
}
cases.append(dict(name="outer_width_and_height_with_border_and_margin", expected=exp3, actual=c3, passed=c3 == exp3))
# Case 4: border-box element: width() still reports pure content width (278), outerWidth() is 300
c4 = page.evaluate("""() => ({
width: $('#div2').width(),
height: $('#div2').height(),
innerWidth: $('#div2').innerWidth(),
outerWidth: $('#div2').outerWidth(),
outerWidthWithMargin: $('#div2').outerWidth(true)
})""")
exp4 = {"width": 278, "height": 78, "innerWidth": 298, "outerWidth": 300, "outerWidthWithMargin": 310}
cases.append(dict(name="border_box_vs_content_box_dimensions", expected=exp4, actual=c4, passed=c4 == exp4))
# Case 5: setting width()/height() and measuring $(window) viewport dimensions
c5 = page.evaluate("""() => {
$('#div1').width(400).height(150);
return {
newWidth: $('#div1').width(),
newHeight: $('#div1').height(),
newOuterWidth: $('#div1').outerWidth(),
winWidth: $(window).width(),
winHeight: $(window).height()
};
}""")
exp5 = {
"newWidth": 400,
"newHeight": 150,
"newOuterWidth": 422,
"winWidth": 1200,
"winHeight": 800,
}
cases.append(dict(name="set_dimensions_and_window_viewport", expected=exp5, actual=c5, passed=c5 == exp5))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 300×100(padding 10/border 1/margin 3)content-box 测得 width 300、innerWidth 320、outerWidth 322、outerWidth(true) 328;同等样式 border-box 测得 width 278、outerWidth 300;动态设为 400×150 后 outerWidth 为 422 且窗口视口为 1200×800。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:4261f396cd1278449d43d93d47566f184c747b38aa7c4de4a10bee2c3ede0858
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:c3f7e4ff881145995d689632a6a655a73775b37bc39b95cebebcddfffe82fd9c
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
一个 `box-sizing: content-box` 的元素设置 `width: 200px; padding: 15px; border: 2px solid; margin: 10px;`,其 `width()`、`innerWidth()`、`outerWidth()` 与 `outerWidth(true)` 分别返回多少像素?
展开参考解答
依次返回 `200`(仅内容区)、`230`(200 + 15×2)、`234`(230 + 2×2)和 `254`(234 + 10×2)。