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

在离线 Chromium 中验证水平/垂直按钮组、尺寸缩放与内嵌下拉菜单

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-button-groups.py
explore-button-groups.py276 行
"""Offline Playwright Chromium verification for Bootstrap 5 Button Groups (Ch 12)."""
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; text-align: center;
    cursor: pointer; 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-group, .btn-group-vertical { position: relative; display: inline-flex; vertical-align: middle; }
  .btn-group > .btn, .btn-group-vertical > .btn { position: relative; flex: 1 1 auto; }
  .btn-group > .btn:not(:first-child),
  .btn-group > .btn-group:not(:first-child) { margin-left: -1px; }
  .btn-group > .btn:not(:last-child):not(.dropdown-toggle),
  .btn-group > .btn-group:not(:last-child) > .btn {
    border-top-right-radius: 0; border-bottom-right-radius: 0;
  }
  .btn-group > .btn:nth-child(n+3),
  .btn-group > :not(.btn-check) + .btn,
  .btn-group > .btn-group:not(:first-child) > .btn {
    border-top-left-radius: 0; border-bottom-left-radius: 0;
  }
  .btn-group-lg > .btn { padding: 0.5rem 1rem; font-size: 1.25rem; border-radius: 0.5rem; }
  .btn-group-sm > .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.25rem; }
  .btn-group-vertical { flex-direction: column; align-items: flex-start; justify-content: center; }
  .btn-group-vertical > .btn, .btn-group-vertical > .btn-group { width: 100%; }
  .btn-group-vertical > .btn:not(:first-child),
  .btn-group-vertical > .btn-group:not(:first-child) { margin-top: -1px; }
  .btn-group-vertical > .btn:not(:last-child):not(.dropdown-toggle),
  .btn-group-vertical > .btn-group:not(:last-child) > .btn {
    border-bottom-right-radius: 0; border-bottom-left-radius: 0;
  }
  .btn-group-vertical > .btn ~ .btn,
  .btn-group-vertical > .btn-group:not(:first-child) > .btn {
    border-top-left-radius: 0; border-top-right-radius: 0;
  }
  .dropdown-toggle::after {
    display: inline-block; margin-left: 0.255em; vertical-align: 0.255em; content: "";
    border-top: 0.3em solid; border-right: 0.3em solid transparent; border-bottom: 0; border-left: 0.3em solid transparent;
  }
  .dropdown-menu {
    position: absolute; top: 100%; left: 0; z-index: 1000; display: none; min-width: 10rem;
    padding: 0.5rem 0; margin: 0.125rem 0 0; list-style: none; background-color: #fff;
    border: 1px solid rgba(0,0,0,.175); border-radius: 0.375rem;
  }
  .dropdown-menu.show { display: block; }
  .dropdown-item { display: block; width: 100%; padding: 0.25rem 1rem; color: #212529; text-decoration: none; }
</style>
</head>
<body>
<section>
  <div id="grp-basic" class="btn-group" role="group">
    <button id="b1" type="button" class="btn btn-primary">Apple</button>
    <button id="b2" type="button" class="btn btn-primary">Samsung</button>
    <button id="b3" type="button" class="btn btn-primary">Sony</button>
  </div>
</section>

<section style="margin-top:16px">
  <div id="grp-lg" class="btn-group btn-group-lg">
    <button id="lg-1" type="button" class="btn btn-primary">Apple</button>
    <button type="button" class="btn btn-primary">Samsung</button>
  </div>
  <div id="grp-sm" class="btn-group btn-group-sm">
    <button id="sm-1" type="button" class="btn btn-primary">Apple</button>
    <button type="button" class="btn btn-primary">Samsung</button>
  </div>
</section>

<section style="margin-top:16px">
  <div id="grp-vert" class="btn-group-vertical">
    <button id="v1" type="button" class="btn btn-primary">Apple</button>
    <button id="v2" type="button" class="btn btn-primary">Samsung</button>
    <button id="v3" type="button" class="btn btn-primary">Sony</button>
  </div>
</section>

<section style="margin-top:16px">
  <div id="grp-nested-h" class="btn-group">
    <button type="button" class="btn btn-primary">Apple</button>
    <button type="button" class="btn btn-primary">Samsung</button>
    <div class="btn-group">
      <button id="h-toggle" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">Sony</button>
      <div id="h-menu" class="dropdown-menu">
        <a class="dropdown-item" href="#">Tablet</a>
        <a class="dropdown-item" href="#">Smartphone</a>
      </div>
    </div>
  </div>
</section>

<section style="margin-top:48px">
  <div id="grp-nested-v" class="btn-group-vertical">
    <button type="button" class="btn btn-primary">Apple</button>
    <button type="button" class="btn btn-primary">Samsung</button>
    <div class="btn-group">
      <button id="v-toggle" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">Sony</button>
      <ul id="v-menu" class="dropdown-menu">
        <li><a class="dropdown-item" href="#">Tablet</a></li>
        <li><a class="dropdown-item" href="#">Smartphone</a></li>
      </ul>
    </div>
  </div>
</section>

<section style="margin-top:48px">
  <div id="inline-g1" class="btn-group">
    <button type="button" class="btn btn-primary">Apple</button>
    <button type="button" class="btn btn-primary">Samsung</button>
    <button type="button" class="btn btn-primary">Sony</button>
  </div>
  <div id="inline-g2" class="btn-group">
    <button type="button" class="btn btn-primary">BMW</button>
    <button type="button" class="btn btn-primary">Mercedes</button>
    <button type="button" class="btn btn-primary">Volvo</button>
  </div>
</section>

<script>
  document.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(btn => {
    btn.addEventListener("click", () => {
      const menu = btn.nextElementSibling;
      const open = menu.classList.toggle("show");
      btn.setAttribute("aria-expanded", String(open));
    });
  });
</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: basic horizontal btn-group
        c1_actual = page.evaluate("""() => {
            const g = getComputedStyle(document.getElementById("grp-basic"));
            const r1 = document.getElementById("b1").getBoundingClientRect();
            const r2 = document.getElementById("b2").getBoundingClientRect();
            const r3 = document.getElementById("b3").getBoundingClientRect();
            const s1 = getComputedStyle(document.getElementById("b1"));
            const s2 = getComputedStyle(document.getElementById("b2"));
            const s3 = getComputedStyle(document.getElementById("b3"));
            return {
                display: g.display,
                same_row: Math.round(r1.top) === Math.round(r2.top) && Math.round(r2.top) === Math.round(r3.top),
                b2_margin_left: s2.marginLeft,
                b1_outer_left_radius: s1.borderTopLeftRadius,
                b1_inner_right_radius: s1.borderTopRightRadius,
                b2_inner_left_radius: s2.borderTopLeftRadius,
                b3_outer_right_radius: s3.borderTopRightRadius,
            };
        }""")
        c1_expected = {
            "display": "inline-flex",
            "same_row": True,
            "b2_margin_left": "-1px",
            "b1_outer_left_radius": "6px",
            "b1_inner_right_radius": "0px",
            "b2_inner_left_radius": "0px",
            "b3_outer_right_radius": "6px",
        }

        # Case 2: btn-group sizes + vertical group
        c2_actual = page.evaluate("""() => {
            const lgH = Math.round(document.getElementById("lg-1").getBoundingClientRect().height);
            const mdH = Math.round(document.getElementById("b1").getBoundingClientRect().height);
            const smH = Math.round(document.getElementById("sm-1").getBoundingClientRect().height);
            const gv = getComputedStyle(document.getElementById("grp-vert"));
            const v1 = document.getElementById("v1").getBoundingClientRect();
            const v2 = document.getElementById("v2").getBoundingClientRect();
            const v3 = document.getElementById("v3").getBoundingClientRect();
            return {
                lg_fs: getComputedStyle(document.getElementById("lg-1")).fontSize,
                sm_fs: getComputedStyle(document.getElementById("sm-1")).fontSize,
                strict_size_order: lgH > mdH && mdH > smH,
                vert_flex_dir: gv.flexDirection,
                vert_stacked: v2.top > v1.top && v3.top > v2.top,
                vert_equal_width: Math.round(v1.width) === Math.round(v2.width) && Math.round(v2.width) === Math.round(v3.width),
            };
        }""")
        c2_expected = {
            "lg_fs": "20px",
            "sm_fs": "14px",
            "strict_size_order": True,
            "vert_flex_dir": "column",
            "vert_stacked": True,
            "vert_equal_width": True,
        }

        # Case 3: nested dropdown in horizontal & vertical groups
        h_before = page.evaluate('getComputedStyle(document.getElementById("h-menu")).display')
        page.click("#h-toggle")
        h_after = page.evaluate("""() => ({
            display: getComputedStyle(document.getElementById("h-menu")).display,
            expanded: document.getElementById("h-toggle").getAttribute("aria-expanded"),
            items: document.querySelectorAll("#h-menu .dropdown-item").length,
        })""")
        page.click("#h-toggle")
        h_closed = page.evaluate('getComputedStyle(document.getElementById("h-menu")).display')

        v_before = page.evaluate('getComputedStyle(document.getElementById("v-menu")).display')
        page.click("#v-toggle")
        v_after = page.evaluate("""() => ({
            display: getComputedStyle(document.getElementById("v-menu")).display,
            expanded: document.getElementById("v-toggle").getAttribute("aria-expanded"),
            items: document.querySelectorAll("#v-menu .dropdown-item").length,
        })""")
        c3_actual = {
            "h_before": h_before,
            "h_open_display": h_after["display"],
            "h_open_expanded": h_after["expanded"],
            "h_items": h_after["items"],
            "h_closed": h_closed,
            "v_before": v_before,
            "v_open_display": v_after["display"],
            "v_open_expanded": v_after["expanded"],
            "v_items": v_after["items"],
        }
        c3_expected = {
            "h_before": "none",
            "h_open_display": "block",
            "h_open_expanded": "true",
            "h_items": 2,
            "h_closed": "none",
            "v_before": "none",
            "v_open_display": "block",
            "v_open_expanded": "true",
            "v_items": 2,
        }

        # Case 4: multiple inline button groups
        c4_actual = page.evaluate("""() => {
            const g1 = document.getElementById("inline-g1").getBoundingClientRect();
            const g2 = document.getElementById("inline-g2").getBoundingClientRect();
            return {
                side_by_side_same_top: Math.round(g1.top) === Math.round(g2.top),
                g2_to_right_of_g1: g2.left >= g1.right,
            };
        }""")
        c4_expected = {"side_by_side_same_top": True, "g2_to_right_of_g1": True}

        browser.close()

    cases = [
        dict(name="basic_group_and_border_radius", description="核对 .btn-group 水平 inline-flex 排列、-1px 边框重叠与内侧圆角归零", expected=c1_expected, actual=c1_actual, passed=c1_actual == c1_expected),
        dict(name="group_sizes_and_vertical", description="核对 .btn-group-lg/sm 尺寸缩放与 .btn-group-vertical 等宽垂直堆叠", expected=c2_expected, actual=c2_actual, passed=c2_actual == c2_expected),
        dict(name="nested_dropdown_horizontal_and_vertical", description="核对水平与垂直按钮组内嵌 data-bs-toggle=dropdown 菜单展开/收起状态", expected=c3_expected, actual=c3_actual, passed=c3_actual == c3_expected),
        dict(name="inline_multiple_groups", description="核对多个独立 .btn-group 并列显示在同一行", 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-button-groups-lab/explore-button-groups.py

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

下载课程关联工程包:Bootstrap5

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

下载课程关联工程包:Bootstrap5

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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