蓝色天空网mbsky.com · 知识 · 实践 · 创造Bootstrap4 · 本地阅读预览
教程 / 前端开发 / Bootstrap4

Bootstrap4 自定义表单

核对 Bootstrap 4 跨浏览器一致的自定义复选框、单选框、内联排布、自定义选择菜单及尺寸、滑块与文件上传控件的结构与交互机制。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

自定义复选框、单选框与同行排布

为了消除不同操作系统与浏览器原生控件的外观差异,Bootstrap 4 提供了一整套自定义表单样式。自定义复选框需用 `<div class="custom-control custom-checkbox">` 包裹 `<input type="checkbox" class="custom-control-input" id="...">` 与匹配相同 `for` 值的 `<label class="custom-control-label">`。本站离线 Chromium 实测:原生 `<input>` 被置为 `opacity: 0`,视觉选框由标签 `::before` 伪元素绘制(圆角 `4px`、未选白底 `rgb(255, 255, 255)`);点击 `<label>` 后勾选状态变为 `true` 且伪元素背景切为主色蓝 `rgb(0, 123, 255)`。

自定义单选框的结构完全对应,只需把容器类换为 `.custom-control.custom-radio`、输入类型改为 `type="radio"` 并保持标签 `for` 与控件 `id` 一致(实测其 `::before` 呈 `border-radius: 50%` 圆形,点击标签即可选中)。若要让多个自定义复选/单选控件同行显示,在每个外层容器上再加 `.custom-control-inline` 即可(实测 `display: inline-flex`,相邻两项处于同一水平行)。

自定义选择菜单与尺寸变体

在 `<select>` 上添加 `.custom-select` 可隐藏系统默认箭头并渲染统一 SVG 指示图标;调整大小时应配合使用 `.custom-select.custom-select-sm` 或 `.custom-select.custom-select-lg`(注意:部分简写片段仅写了 `.custom-select-sm`/`.custom-select-lg` 而漏写基础类 `.custom-select`,在标准 Bootstrap 4 中必须同时保留 `.custom-select` 才能完整继承边框、圆角与背景箭头)。本站离线 Chromium 实测:`.custom-select` 计算为 `appearance: none` 并载入内联 SVG 背景图,三档高度严格对应 `[31, 38, 48]` 像素。

自定义滑块与文件上传控件

为 `<input type="range">` 添加 `.custom-range` 可获得全宽一致的滑块轨道样式。本站实测其占满 `480px` 容器宽度且交互设值 `"75"` 正常生效。

自定义文件上传控件由 `.custom-file` 容器包裹透明的 `<input type="file" class="custom-file-input" id="customFile">` 和匹配 `for` 的 `<label class="custom-file-label">` 组成。实测原生文件控件 `opacity: 0`、标签高 `38px` 且右侧 `::after` 渲染 `"Browse"` 按钮区;由于浏览器不会自动把选中文件名回填到 `<label>`,配合 `change` 事件更新文本后标签内容即可实时显示为 `"report.pdf"`。

离线 Chromium 实测自定义复选/单选伪元素切换、选择菜单三档高度及滑块/文件控件

python · 阅读源码
"""Offline Playwright Chromium lab for Bootstrap 4 Chapter 26 (forms-custom)."""
import json
from playwright.sync_api import sync_playwright

BS4_CUSTOM_CSS = """
* { box-sizing: border-box; }
body { margin: 16px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 16px; line-height: 1.5; }
.wrap { width: 480px; }
.custom-control { position: relative; z-index: 1; display: block; min-height: 1.5rem; padding-left: 1.5rem; }
.custom-control-inline { display: inline-flex; margin-right: 1rem; }
.custom-control-input { position: absolute; left: 0; z-index: -1; width: 1rem; height: 1.25rem; opacity: 0; }
.custom-control-label { position: relative; display: inline-block; margin-bottom: 0; vertical-align: top; cursor: pointer; }
.custom-control-label::before {
  position: absolute; top: 0.25rem; left: -1.5rem; display: block; width: 1rem; height: 1rem;
  pointer-events: none; content: ""; background-color: #fff; border: 1px solid #adb5bd;
}
.custom-checkbox .custom-control-label::before { border-radius: 0.25rem; }
.custom-radio .custom-control-label::before { border-radius: 50%; }
.custom-control-input:checked ~ .custom-control-label::before {
  color: #fff; border-color: #007bff; background-color: #007bff;
}
.custom-select {
  display: inline-block; width: 100%; height: 38px; padding: 0.375rem 1.75rem 0.375rem 0.75rem;
  font-size: 1rem; line-height: 1.5; color: #495057; vertical-align: middle;
  background: #fff url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='5' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") no-repeat right 0.75rem center/8px 10px;
  border: 1px solid #ced4da; border-radius: 0.25rem; appearance: none; -webkit-appearance: none;
}
.custom-select-sm { height: 31px; padding-top: 0.25rem; padding-bottom: 0.25rem; padding-left: 0.5rem; font-size: 0.875rem; }
.custom-select-lg { height: 48px; padding-top: 0.5rem; padding-bottom: 0.5rem; padding-left: 1rem; font-size: 1.25rem; }
.custom-range { width: 100%; height: 1.4rem; padding: 0; background-color: transparent; appearance: none; -webkit-appearance: none; }
.custom-file { position: relative; display: inline-block; width: 100%; height: 38px; margin-bottom: 0; }
.custom-file-input { position: relative; z-index: 2; width: 100%; height: 38px; margin: 0; opacity: 0; }
.custom-file-label {
  position: absolute; top: 0; right: 0; left: 0; z-index: 1; height: 38px;
  padding: 0.375rem 0.75rem; line-height: 1.5; color: #495057; background-color: #fff;
  border: 1px solid #ced4da; border-radius: 0.25rem;
}
.custom-file-label::after {
  position: absolute; top: 0; right: 0; bottom: 0; z-index: 3; display: block; height: 36px;
  padding: 0.375rem 0.75rem; line-height: 1.5; color: #495057; content: "Browse";
  background-color: #e9ecef; border-left: inherit; border-radius: 0 0.25rem 0.25rem 0;
}
"""


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


def run():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 800, "height": 700})
        page.set_content(f"""<!DOCTYPE html><html><head><style>{BS4_CUSTOM_CSS}</style></head><body>
        <div class="wrap">
          <div class="custom-control custom-checkbox">
            <input type="checkbox" class="custom-control-input" id="customCheck" name="example1">
            <label id="lbl-cb" class="custom-control-label" for="customCheck">自定义复选框</label>
          </div>
          <div class="custom-control custom-radio">
            <input type="radio" class="custom-control-input" id="customRadio" name="example1" value="customEx">
            <label id="lbl-rd" class="custom-control-label" for="customRadio">自定义单选框</label>
          </div>
          <div id="inline-group">
            <div class="custom-control custom-radio custom-control-inline">
              <input type="radio" class="custom-control-input" id="cr1" name="inex" value="1">
              <label class="custom-control-label" for="cr1">自定义单选框 1</label>
            </div>
            <div class="custom-control custom-radio custom-control-inline">
              <input type="radio" class="custom-control-input" id="cr2" name="inex" value="2">
              <label class="custom-control-label" for="cr2">自定义单选框 2</label>
            </div>
          </div>

          <select id="sel-def" class="custom-select"><option value="a">Default</option><option value="b">Opt B</option></select>
          <select id="sel-sm" class="custom-select custom-select-sm"><option>Small</option></select>
          <select id="sel-lg" class="custom-select custom-select-lg"><option>Large</option></select>

          <label for="customRange">自定义滑块控件</label>
          <input type="range" class="custom-range" id="customRange" min="0" max="100" value="50">

          <div class="custom-file">
            <input type="file" class="custom-file-input" id="customFile">
            <label id="file-lbl" class="custom-file-label" for="customFile">选择文件</label>
          </div>
        </div>
        <script>
        document.querySelector('#customFile').addEventListener('change', function() {{
          const name = this.dataset.mockFile || (this.files && this.files[0] ? this.files[0].name : '选择文件');
          document.querySelector('#file-lbl').textContent = name;
        }});
        </script></body></html>""")

        # Case 1: custom checkbox, custom radio, inline layout
        cb_before_bg = page.evaluate("() => getComputedStyle(document.querySelector('#lbl-cb'), '::before').backgroundColor")
        page.click("#lbl-cb")
        page.click("#lbl-rd")
        actual1 = page.evaluate("""(cbBeforeBg) => {
          const cbBefore = getComputedStyle(document.querySelector('#lbl-cb'), '::before');
          const rdBefore = getComputedStyle(document.querySelector('#lbl-rd'), '::before');
          const inl = Array.from(document.querySelectorAll('#inline-group .custom-control-inline'));
          return {
            native_input_opacity: getComputedStyle(document.querySelector('#customCheck')).opacity,
            checkbox_before_bg_unchecked: cbBeforeBg,
            checkbox_checked_after_label_click: document.querySelector('#customCheck').checked,
            checkbox_before_bg_checked: cbBefore.backgroundColor,
            checkbox_radius: cbBefore.borderRadius,
            radio_radius: rdBefore.borderRadius,
            radio_checked_after_label_click: document.querySelector('#customRadio').checked,
            inline_display: getComputedStyle(inl[0]).display,
            inline_same_row: Math.abs(inl[0].getBoundingClientRect().top - inl[1].getBoundingClientRect().top) <= 1,
          };
        }""", cb_before_bg)
        expected1 = {
            "native_input_opacity": "0",
            "checkbox_before_bg_unchecked": "rgb(255, 255, 255)",
            "checkbox_checked_after_label_click": True,
            "checkbox_before_bg_checked": "rgb(0, 123, 255)",
            "checkbox_radius": "4px",
            "radio_radius": "50%",
            "radio_checked_after_label_click": True,
            "inline_display": "inline-flex",
            "inline_same_row": True,
        }
        cases.append(dict(
            name="custom_checkbox_radio_and_inline",
            expected=expected1,
            actual=actual1,
            passed=(actual1 == expected1),
        ))

        # Case 2: custom select & sm/lg sizes
        page.select_option("#sel-def", "b")
        actual2 = page.evaluate("""() => ({
          appearance: getComputedStyle(document.querySelector('#sel-def')).appearance,
          has_svg_caret_bg: getComputedStyle(document.querySelector('#sel-def')).backgroundImage.includes('data:image/svg+xml'),
          selected_value: document.querySelector('#sel-def').value,
          heights_sm_def_lg_px: [
            Math.round(document.querySelector('#sel-sm').getBoundingClientRect().height),
            Math.round(document.querySelector('#sel-def').getBoundingClientRect().height),
            Math.round(document.querySelector('#sel-lg').getBoundingClientRect().height),
          ],
        })""")
        expected2 = {
            "appearance": "none",
            "has_svg_caret_bg": True,
            "selected_value": "b",
            "heights_sm_def_lg_px": [31, 38, 48],
        }
        cases.append(dict(
            name="custom_select_and_sizes",
            expected=expected2,
            actual=actual2,
            passed=(actual2 == expected2),
        ))

        # Case 3: custom range & custom file
        page.evaluate("""() => {
          const r = document.querySelector('#customRange');
          r.value = '75';
          const f = document.querySelector('#customFile');
          f.dataset.mockFile = 'report.pdf';
          f.dispatchEvent(new Event('change'));
        }""")
        actual3 = page.evaluate("""() => {
          const r = document.querySelector('#customRange');
          const fi = document.querySelector('#customFile');
          const fl = document.querySelector('#file-lbl');
          return {
            range_width_px: Math.round(r.getBoundingClientRect().width),
            range_value: r.value,
            file_input_opacity: getComputedStyle(fi).opacity,
            file_label_height_px: Math.round(fl.getBoundingClientRect().height),
            file_label_after_content: getComputedStyle(fl, '::after').content,
            file_label_updated_text: fl.textContent,
          };
        }""")
        expected3 = {
            "range_width_px": 480,
            "range_value": "75",
            "file_input_opacity": "0",
            "file_label_height_px": 38,
            "file_label_after_content": '"Browse"',
            "file_label_updated_text": "report.pdf",
        }
        cases.append(dict(
            name="custom_range_and_file",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

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


if __name__ == "__main__":
    run()
预期结果 · 待实际运行核验
  • 核对原生 input 透明度 0 与标签 ::before 选中变蓝、.custom-control-inline 同行、.custom-select 高度 [31, 38, 48]px,以及 range 赋 75 和 custom-file 标签文件名回显。
离线 Chromium 实测自定义复选/单选伪元素切换、选择菜单三档高度及滑块/文件控件

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

当前源码 SHA256:adbdfe5bde1651a8bafc569ed00510c94fc525026f2e07fd10be8f1b5e8fec3c

下载本站示例源码

本地运行

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

下载Bootstrap4 自定义表单实验

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

ZIP SHA256:80d093c7f4fc74681dfa6aa211ea4456a2a8ef8c52008bdd23f34d3e5ecd7824

常见错误与边界

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

练习与解答

在 `.custom-checkbox` 与 `.custom-file` 中,如果忘记让 `<label>` 的 `for` 属性与 `<input>` 的 `id` 匹配,会出现什么问题?

展开参考解答

原生 `<input>` 处于透明隐藏状态,用户实际点击的是可见的 `<label>` 及其伪元素;若 `for` 与 `id` 不一致,点击标签将无法触发复选框勾选切换或唤起文件选择对话框。

规范与官方依据