蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery 教程目录 40章
jQuery / LEARN BY DOING

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 差异与视口尺寸

含完整源码 · 233 行
展开查看收起
python
"""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。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a885.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a885.zip

下载课程关联工程包:jQuery

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

依次返回 `200`(仅内容区)、`230`(200 + 15×2)、`234`(230 + 2×2)和 `254`(234 + 10×2)。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习