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

Bootstrap5 复选框与单选框

系统说明 Bootstrap 5 复选框、单选框、胶囊切换开关(`.form-switch`)与行内排列(`.form-check-inline`)的标记结构和选中/禁用状态,并附无头 Chromium 实测结果。

学完这一章,你能够

  • 系统说明 Bootstrap 5 复选框、单选框、胶囊切换开关(`.form-switch`)与行内排列(`.form-check-inline`)的标记结构和选中/禁用状态,并附无头 Chromium 实测结果。

复选框结构、默认选中与行内排列

当需要允许用户在多个预设选项中任选零项或多项时,应使用复选框。Bootstrap 5 通过外层 `.form-check` 预留左内边距与垂直间距,内部使用 `<input type="checkbox" class="form-check-input">` 搭配 `<label class="form-check-label">`,并借助 `checked` 属性声明默认勾选状态。建议始终用 `for` 与 `id` 精确配对标签与控件,以扩大可点击区域;若需将多项水平并排,只需在 `.form-check` 上追加 `.form-check-inline`(`display: inline-block`)。本站离线 Chromium 实测:默认勾选的 `check1` 点击 `<label for="check1">` 后切换为 `false`,`check2` 点击后变为 `true` 且背景着色为 `rgb(13, 110, 253)`,`disabled` 项 `opacity` 降至 `0.5`;`.form-check-inline` 两项顶边齐平并水平相邻。

单选框分组互斥

单选框用于从一组互斥选项中仅选其一,核心条件是同组 `<input type="radio" class="form-check-input">` 必须共享相同的 `name` 属性(如 `name="optradio"`),并可将选项文字放在关联的 `<label class="form-check-label" for="...">` 内以提升无障碍体验;添加 `disabled` 可禁用特定选项。Chromium 实测点击同组第 2 项 `r2` 后,`r1.checked` 自动取消为 `false`,`r2.checked` 为 `true` 且呈现正圆 `border-radius: 50%` 与蓝色背景 `rgb(13, 110, 253)`,`r3` 保持禁用状态。

切换开关(.form-switch)

在 `.form-check` 容器上同时添加 `.form-switch`,即可将标准复选框渲染为胶囊形滑动开关(语义上仍是 `type="checkbox"`,可选配 `role="switch"` 增强读屏支持)。Chromium 实测开启态开关宽 `32px`(`2em`)、背景色 `rgb(13, 110, 253)`、滑块位置 `100% 50%`;点击关闭后 `checked` 变为 `false`,背景色回落为 `rgb(255, 255, 255)`,滑块左移至 `0% 50%`。

运行 Bootstrap 5 复选框、单选框互斥、切换开关与行内排布实验

含完整源码 · 168 行
展开查看收起
python
"""Offline Playwright Chromium verification for Bootstrap 5 Checkboxes, Radios, and Switches."""
import json
from playwright.sync_api import sync_playwright

CSS = """
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; font-size: 16px; line-height: 1.5; }
input { font-family: inherit; font-size: inherit; }
.form-check { display: block; min-height: 1.5rem; padding-left: 1.5em; margin-bottom: 0.125rem; }
.form-check-inline { display: inline-block; margin-right: 1rem; }
.form-check-input {
  width: 1em; height: 1em; margin-top: 0.25em; vertical-align: top;
  background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.25); appearance: none;
  float: left; margin-left: -1.5em;
}
.form-check-input[type="checkbox"] { border-radius: 0.25em; }
.form-check-input[type="radio"] { border-radius: 50%; }
.form-check-input:checked { background-color: #0d6efd; border-color: #0d6efd; }
.form-check-input:disabled { pointer-events: none; opacity: 0.5; }
.form-switch { padding-left: 2.5em; }
.form-switch .form-check-input {
  width: 2em; margin-left: -2.5em; border-radius: 2em;
  background-position: left center;
}
.form-switch .form-check-input:checked { background-position: right center; }
"""


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


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 800, "height": 600})

        # Case 1: checkboxes + label binding + disabled
        page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
        <div class="form-check">
          <input class="form-check-input" type="checkbox" id="check1" name="opt1" value="yes" checked>
          <label id="lbl1" class="form-check-label" for="check1">Option 1</label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="checkbox" id="check2" name="opt2">
          <label class="form-check-label" for="check2">Option 2</label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="checkbox" id="check3" disabled>
          <label class="form-check-label" for="check3">Disabled</label>
        </div></body></html>""")
        before1 = page.is_checked("#check1")
        page.click("#lbl1")
        page.click("#check2")
        act1 = page.evaluate("""(before1) => {
          const c1 = document.getElementById('check1');
          const c2 = document.getElementById('check2');
          const c3 = document.getElementById('check3');
          return {
            c1_initial: before1,
            c1_after_label_click: c1.checked,
            c2_checked: c2.checked,
            c2_bg: getComputedStyle(c2).backgroundColor,
            c3_disabled: c3.disabled,
            c3_opacity: getComputedStyle(c3).opacity,
          };
        }""", before1)
        exp1 = {
            "c1_initial": True,
            "c1_after_label_click": False,
            "c2_checked": True,
            "c2_bg": "rgb(13, 110, 253)",
            "c3_disabled": True,
            "c3_opacity": "0.5",
        }
        cases.append({"name": "checkbox_states_and_label_binding", "expected": exp1, "actual": act1, "passed": act1 == exp1})

        # Case 2: radio mutual exclusion
        page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
        <div class="form-check">
          <input type="radio" class="form-check-input" id="r1" name="optradio" value="option1" checked>
          <label class="form-check-label" for="r1">Option 1</label>
        </div>
        <div class="form-check">
          <input type="radio" class="form-check-input" id="r2" name="optradio" value="option2">
          <label class="form-check-label" for="r2">Option 2</label>
        </div>
        <div class="form-check">
          <input type="radio" class="form-check-input" id="r3" name="optradio" disabled>
          <label class="form-check-label" for="r3">Option 3</label>
        </div></body></html>""")
        page.click("#r2")
        act2 = page.evaluate("""() => {
          const r1 = document.getElementById('r1');
          const r2 = document.getElementById('r2');
          const r3 = document.getElementById('r3');
          return {
            r1_checked: r1.checked,
            r2_checked: r2.checked,
            r2_radius: getComputedStyle(r2).borderRadius,
            r2_bg: getComputedStyle(r2).backgroundColor,
            r3_disabled: r3.disabled,
          };
        }""")
        exp2 = {
            "r1_checked": False,
            "r2_checked": True,
            "r2_radius": "50%",
            "r2_bg": "rgb(13, 110, 253)",
            "r3_disabled": True,
        }
        cases.append({"name": "radio_mutual_exclusion", "expected": exp2, "actual": act2, "passed": act2 == exp2})

        # Case 3: form-switch
        page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
        <div class="form-check form-switch">
          <input class="form-check-input" type="checkbox" id="sw" name="darkmode" value="yes" checked>
          <label class="form-check-label" for="sw">Dark Mode</label>
        </div></body></html>""")
        on_state = page.evaluate("""() => {
          const sw = document.getElementById('sw');
          const cs = getComputedStyle(sw);
          return { checked: sw.checked, width: Math.round(sw.getBoundingClientRect().width), bg: cs.backgroundColor, bgPos: cs.backgroundPosition };
        }""")
        page.click("#sw")
        off_state = page.evaluate("""() => {
          const sw = document.getElementById('sw');
          const cs = getComputedStyle(sw);
          return { checked: sw.checked, bg: cs.backgroundColor, bgPos: cs.backgroundPosition };
        }""")
        act3 = {"on": on_state, "off": off_state}
        exp3 = {
            "on": {"checked": True, "width": 32, "bg": "rgb(13, 110, 253)", "bgPos": "100% 50%"},
            "off": {"checked": False, "bg": "rgb(255, 255, 255)", "bgPos": "0% 50%"},
        }
        cases.append({"name": "switch_toggle_styles", "expected": exp3, "actual": act3, "passed": act3 == exp3})

        # Case 4: form-check-inline vs stacked form-check
        page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
        <div id="s1" class="form-check"><input class="form-check-input" type="checkbox"><label>S1</label></div>
        <div id="s2" class="form-check"><input class="form-check-input" type="checkbox"><label>S2</label></div>
        <div>
          <div id="i1" class="form-check form-check-inline"><input class="form-check-input" type="checkbox"><label>I1</label></div>
          <div id="i2" class="form-check form-check-inline"><input class="form-check-input" type="checkbox"><label>I2</label></div>
        </div></body></html>""")
        act4 = page.evaluate("""() => {
          const rc = id => document.getElementById(id).getBoundingClientRect();
          return {
            stacked_vertical: rc('s2').top >= rc('s1').bottom,
            inline_display: getComputedStyle(document.getElementById('i1')).display,
            inline_same_top: Math.round(rc('i1').top) === Math.round(rc('i2').top),
            inline_x2_gt_x1: rc('i2').left > rc('i1').right,
          };
        }""")
        exp4 = {"stacked_vertical": True, "inline_display": "inline-block", "inline_same_top": True, "inline_x2_gt_x1": True}
        cases.append({"name": "inline_check_layout", "expected": exp4, "actual": act4, "passed": act4 == exp4})

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对复选框标签联动与禁用态 0.5 透明度、单选框同 name 互斥与 50% 圆角、.form-switch 32px 胶囊开关开/关背景与位置切换及 .form-check-inline 水平同行布局。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Bootstrap5

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

下载课程关联工程包:Bootstrap5

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

缺少相同 `name` 属性时,两个单选框不会互斥,点击后者不会自动取消前者;将复选框改为开关样式需在 `.form-check` 容器上添加 `.form-switch` 类。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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