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

在离线 Chromium 中验证语义按钮、轮廓悬停、d-grid 块级按钮及加载态

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-buttons.py
explore-buttons.py309 行
"""Offline Playwright Chromium verification for Bootstrap 5 Buttons (Ch 11)."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<style>
  *, *::before, *::after { box-sizing: border-box; }
  html { font-size: 16px; }
  body { margin: 16px; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; line-height: 1.5; }
  .btn {
    display: inline-block;
    font-weight: 400;
    line-height: 1.5;
    color: #212529;
    text-align: center;
    text-decoration: none;
    vertical-align: middle;
    cursor: pointer;
    user-select: none;
    background-color: transparent;
    border: 1px solid transparent;
    padding: 0.375rem 0.75rem;
    font-size: 1rem;
    border-radius: 0.375rem;
  }
  .btn-primary { color: #fff; background-color: #0d6efd; border-color: #0d6efd; }
  .btn-primary.active { color: #fff; background-color: #0a58ca; border-color: #0a53be; }
  .btn-secondary { color: #fff; background-color: #6c757d; border-color: #6c757d; }
  .btn-success { color: #fff; background-color: #198754; border-color: #198754; }
  .btn-info { color: #000; background-color: #0dcaf0; border-color: #0dcaf0; }
  .btn-warning { color: #000; background-color: #ffc107; border-color: #ffc107; }
  .btn-danger { color: #fff; background-color: #dc3545; border-color: #dc3545; }
  .btn-dark { color: #fff; background-color: #212529; border-color: #212529; }
  .btn-light { color: #000; background-color: #f8f9fa; border-color: #f8f9fa; }
  .btn-link { color: #0d6efd; text-decoration: underline; background-color: transparent; border-color: transparent; }

  .btn-outline-primary { color: #0d6efd; border-color: #0d6efd; background-color: transparent; }
  .btn-outline-primary:hover { color: #fff; background-color: #0d6efd; border-color: #0d6efd; }
  .btn-outline-secondary { color: #6c757d; border-color: #6c757d; }
  .btn-outline-success { color: #198754; border-color: #198754; }
  .btn-outline-info { color: #0dcaf0; border-color: #0dcaf0; }
  .btn-outline-warning { color: #ffc107; border-color: #ffc107; }
  .btn-outline-danger { color: #dc3545; border-color: #dc3545; }
  .btn-outline-dark { color: #212529; border-color: #212529; }
  .btn-outline-light { color: #f8f9fa; border-color: #f8f9fa; }
  .text-dark { color: #212529 !important; }

  .btn-lg { padding: 0.5rem 1rem; font-size: 1.25rem; border-radius: 0.5rem; }
  .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.25rem; }

  /* Bootstrap 5 removed .btn-block; block buttons rely on .d-grid + .gap-* */
  .d-grid { display: grid !important; }
  .gap-3 { gap: 1rem !important; }

  .btn:disabled, .btn.disabled { pointer-events: none; opacity: 0.65; }

  @keyframes spinner-border { to { transform: rotate(360deg); } }
  @keyframes spinner-grow {
    0% { transform: scale(0); opacity: 0; }
    50% { opacity: 1; }
    100% { transform: scale(1); opacity: 0; }
  }
  .spinner-border {
    display: inline-block; width: 2rem; height: 2rem; vertical-align: -0.125em;
    border: 0.25em solid currentColor; border-right-color: transparent; border-radius: 50%;
    animation: 0.75s linear infinite spinner-border;
  }
  .spinner-border-sm { width: 1rem; height: 1rem; border-width: 0.2em; }
  .spinner-grow {
    display: inline-block; width: 2rem; height: 2rem; vertical-align: -0.125em;
    background-color: currentColor; border-radius: 50%;
    animation: 0.75s linear infinite spinner-grow;
  }
  .spinner-grow-sm { width: 1rem; height: 1rem; }
  .wrap-600 { width: 600px; }
</style>
</head>
<body>
<section id="sec-variants">
  <button id="b-base" type="button" class="btn">基本按钮</button>
  <button id="b-primary" type="button" class="btn btn-primary">主要按钮</button>
  <button id="b-secondary" type="button" class="btn btn-secondary">次要按钮</button>
  <button id="b-success" type="button" class="btn btn-success">成功</button>
  <button id="b-info" type="button" class="btn btn-info">信息</button>
  <button id="b-warning" type="button" class="btn btn-warning">警告</button>
  <button id="b-danger" type="button" class="btn btn-danger">危险</button>
  <button id="b-dark" type="button" class="btn btn-dark">黑色</button>
  <button id="b-light" type="button" class="btn btn-light">浅色</button>
  <button id="b-link" type="button" class="btn btn-link">链接</button>
</section>

<section id="sec-elements">
  <a id="el-a" href="#" class="btn btn-info" role="button">链接按钮</a>
  <button id="el-btn" type="button" class="btn btn-info">按钮</button>
  <input id="el-input-btn" type="button" class="btn btn-info" value="输入框按钮">
  <input id="el-submit" type="submit" class="btn btn-info" value="提交按钮">
  <input id="el-reset" type="reset" class="btn btn-info" value="重置按钮">
</section>

<section id="sec-outline">
  <button id="o-primary" type="button" class="btn btn-outline-primary">主要按钮</button>
  <button id="o-light" type="button" class="btn btn-outline-light text-dark">浅色</button>
</section>

<section id="sec-sizes">
  <button id="sz-lg" type="button" class="btn btn-primary btn-lg">大号按钮</button>
  <button id="sz-md" type="button" class="btn btn-primary">默认按钮</button>
  <button id="sz-sm" type="button" class="btn btn-primary btn-sm">小号按钮</button>
</section>

<section id="sec-grid" class="wrap-600">
  <div id="no-grid-wrap">
    <button id="legacy-block-only" type="button" class="btn btn-primary btn-block">仅含已废弃 btn-block</button>
  </div>
  <div id="grid-single" class="d-grid">
    <button id="grid-btn-1" type="button" class="btn btn-primary">块级按钮 1</button>
  </div>
  <div id="grid-multi" class="d-grid gap-3">
    <button id="gm-1" type="button" class="btn btn-primary">100% 宽度按钮 1</button>
    <button id="gm-2" type="button" class="btn btn-primary">100% 宽度按钮 2</button>
    <button id="gm-3" type="button" class="btn btn-primary">100% 宽度按钮 3</button>
  </div>
</section>

<section id="sec-states">
  <button id="st-active" type="button" class="btn btn-primary active">激活按钮</button>
  <button id="st-disabled-btn" type="button" class="btn btn-primary" disabled>禁用按钮</button>
  <a id="st-disabled-a" href="#" class="btn btn-primary disabled" tabindex="-1" aria-disabled="true">禁用链接</a>
</section>

<section id="sec-spinners">
  <button id="sp-1" type="button" class="btn btn-primary"><span id="sp-icon-1" class="spinner-border spinner-border-sm"></span></button>
  <button id="sp-2" type="button" class="btn btn-primary"><span class="spinner-border spinner-border-sm"></span> Loading..</button>
  <button id="sp-3" type="button" class="btn btn-primary" disabled><span class="spinner-border spinner-border-sm"></span> Loading..</button>
  <button id="sp-4" type="button" class="btn btn-primary" disabled><span id="sp-icon-4" class="spinner-grow spinner-grow-sm"></span> Loading..</button>
</section>
<script>
  window.__clicks = 0;
  document.getElementById("st-disabled-btn").addEventListener("click", () => { window.__clicks += 1; });
</script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1000, "height": 800})
        page.set_content(HTML, wait_until="load")

        # Case 1: variants + multi-element buttons
        c1_actual = page.evaluate("""() => {
            const bg = id => getComputedStyle(document.getElementById(id)).backgroundColor;
            const col = id => getComputedStyle(document.getElementById(id)).color;
            const els = ["el-a", "el-btn", "el-input-btn", "el-submit", "el-reset"];
            const allInfoBg = els.every(id => bg(id) === "rgb(13, 202, 240)");
            const allRadius = els.every(id => getComputedStyle(document.getElementById(id)).borderTopLeftRadius === "6px");
            return {
                primary_bg: bg("b-primary"),
                success_bg: bg("b-success"),
                danger_bg: bg("b-danger"),
                warning_bg: bg("b-warning"),
                dark_bg: bg("b-dark"),
                link_bg: bg("b-link"),
                link_color: col("b-link"),
                all_five_elements_consistent: allInfoBg && allRadius,
                a_role: document.getElementById("el-a").getAttribute("role"),
            };
        }""")
        c1_expected = {
            "primary_bg": "rgb(13, 110, 253)",
            "success_bg": "rgb(25, 135, 84)",
            "danger_bg": "rgb(220, 53, 69)",
            "warning_bg": "rgb(255, 193, 7)",
            "dark_bg": "rgb(33, 37, 41)",
            "link_bg": "rgba(0, 0, 0, 0)",
            "link_color": "rgb(13, 110, 253)",
            "all_five_elements_consistent": True,
            "a_role": "button",
        }

        # Case 2: outline hover + sizes
        outline_before = page.evaluate("""() => {
            const s = getComputedStyle(document.getElementById("o-primary"));
            return { bg: s.backgroundColor, color: s.color, border: s.borderTopColor };
        }""")
        page.locator("#o-primary").hover()
        outline_after = page.evaluate("""() => {
            const s = getComputedStyle(document.getElementById("o-primary"));
            return { bg: s.backgroundColor, color: s.color };
        }""")
        sizes = page.evaluate("""() => {
            const m = id => {
                const el = document.getElementById(id);
                const s = getComputedStyle(el);
                return { fs: s.fontSize, pad: s.padding, h: Math.round(el.getBoundingClientRect().height) };
            };
            const lg = m("sz-lg"), md = m("sz-md"), sm = m("sz-sm");
            return {
                lg_fs: lg.fs, md_fs: md.fs, sm_fs: sm.fs,
                lg_pad: lg.pad, md_pad: md.pad, sm_pad: sm.pad,
                strict_height_order: lg.h > md.h && md.h > sm.h,
                light_text_dark: getComputedStyle(document.getElementById("o-light")).color,
            };
        }""")
        c2_actual = {
            "outline_before_bg": outline_before["bg"],
            "outline_before_color": outline_before["color"],
            "outline_hover_bg": outline_after["bg"],
            "outline_hover_color": outline_after["color"],
            "light_text_dark": sizes["light_text_dark"],
            "lg_fs": sizes["lg_fs"],
            "md_fs": sizes["md_fs"],
            "sm_fs": sizes["sm_fs"],
            "strict_height_order": sizes["strict_height_order"],
        }
        c2_expected = {
            "outline_before_bg": "rgba(0, 0, 0, 0)",
            "outline_before_color": "rgb(13, 110, 253)",
            "outline_hover_bg": "rgb(13, 110, 253)",
            "outline_hover_color": "rgb(255, 255, 255)",
            "light_text_dark": "rgb(33, 37, 41)",
            "lg_fs": "20px",
            "md_fs": "16px",
            "sm_fs": "14px",
            "strict_height_order": True,
        }

        # Case 3: BS5 d-grid + gap-3 vs legacy .btn-block
        c3_actual = page.evaluate("""() => {
            const legacyW = Math.round(document.getElementById("legacy-block-only").getBoundingClientRect().width);
            const gridBtnW = Math.round(document.getElementById("grid-btn-1").getBoundingClientRect().width);
            const gm1 = document.getElementById("gm-1").getBoundingClientRect();
            const gm2 = document.getElementById("gm-2").getBoundingClientRect();
            const multiStyle = getComputedStyle(document.getElementById("grid-multi"));
            return {
                legacy_btn_block_is_not_full_width: legacyW < 300,
                d_grid_button_width_px: gridBtnW,
                multi_display: multiStyle.display,
                multi_row_gap: multiStyle.rowGap,
                measured_gap_px: Math.round(gm2.top - gm1.bottom),
            };
        }""")
        c3_expected = {
            "legacy_btn_block_is_not_full_width": True,
            "d_grid_button_width_px": 600,
            "multi_display": "grid",
            "multi_row_gap": "16px",
            "measured_gap_px": 16,
        }

        # Case 4: active, disabled button vs disabled link, loading spinner buttons
        page.evaluate("""() => { document.getElementById("st-disabled-btn").click(); }""")
        c4_actual = page.evaluate("""() => {
            const act = getComputedStyle(document.getElementById("st-active"));
            const disBtn = document.getElementById("st-disabled-btn");
            const disBtnStyle = getComputedStyle(disBtn);
            const disA = getComputedStyle(document.getElementById("st-disabled-a"));
            const sp1 = getComputedStyle(document.getElementById("sp-icon-1"));
            const sp4 = getComputedStyle(document.getElementById("sp-icon-4"));
            return {
                active_bg: act.backgroundColor,
                disabled_btn_prop: disBtn.disabled,
                disabled_btn_opacity: disBtnStyle.opacity,
                disabled_btn_clicks: window.__clicks,
                disabled_link_pointer_events: disA.pointerEvents,
                disabled_link_opacity: disA.opacity,
                spinner_border_sm_wh: [sp1.width, sp1.height],
                spinner_grow_sm_wh: [sp4.width, sp4.height],
                loading_disabled_count: document.querySelectorAll("#sec-spinners button:disabled").length,
            };
        }""")
        c4_expected = {
            "active_bg": "rgb(10, 88, 202)",
            "disabled_btn_prop": True,
            "disabled_btn_opacity": "0.65",
            "disabled_btn_clicks": 0,
            "disabled_link_pointer_events": "none",
            "disabled_link_opacity": "0.65",
            "spinner_border_sm_wh": ["16px", "16px"],
            "spinner_grow_sm_wh": ["16px", "16px"],
            "loading_disabled_count": 2,
        }

        browser.close()

    cases = [
        dict(name="button_variants_and_elements", description="核对语义按钮颜色与 a/button/input 元素统一渲染", expected=c1_expected, actual=c1_actual, passed=c1_actual == c1_expected),
        dict(name="button_outline_and_sizes", description="核对轮廓按钮悬停反色与 btn-lg/默认/btn-sm 尺寸梯度", expected=c2_expected, actual=c2_actual, passed=c2_actual == c2_expected),
        dict(name="button_block_d_grid_gap", description="核对 BS5 移除 btn-block 后由 d-grid 与 gap-3 控制块级按钮", expected=c3_expected, actual=c3_actual, passed=c3_actual == c3_expected),
        dict(name="button_states_and_spinner", description="核对 active/disabled 状态、a.disabled 禁用及加载按钮内嵌旋转器", expected=c4_expected, actual=c4_actual, passed=c4_actual == c4_expected),
    ]
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/bootstrap5-buttons-lab/explore-buttons.py

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

下载课程关联工程包:Bootstrap5

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

下载课程关联工程包:Bootstrap5

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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