蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线 Chromium 实测 CSS 盒模型六大尺寸方法、border-box 差异与视口尺寸

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-dimensions.py
explore-dimensions.py233 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/jquery-dimensions-lab/explore-dimensions.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-dimensions.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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