Bootstrap4 表单控件
核对 Bootstrap 4 支持的五大基础表单控件(input、textarea、checkbox、radio、select)的样式类、垂直/内联排版、禁用态及单选多选交互行为。
学完这一章,你能够
- 核对 Bootstrap 4 支持的五大基础表单控件(input、textarea、checkbox、radio、select)的样式类、垂直/内联排版、禁用态及单选多选交互行为。
支持的控件类型、Input 与 Textarea
Bootstrap 4 对五类常用 HTML 表单控件提供统一样式支持:`input`、`textarea`、`checkbox`、`radio` 与 `select`。
对于 `<input>`,Bootstrap 兼容全部 HTML5 输入类型(`text`、`password`、`datetime`、`datetime-local`、`date`、`month`、`time`、`week`、`number`、`email`、`url`、`search`、`tel`、`color`);务必正确声明 `type` 属性,避免依赖隐式默认类型导致部分样式选择器失效。给 `<input>` 和多行 `<textarea rows="5">` 添加 `.form-control` 并放入 `.form-group` 即可获得一致边框与全宽外观。本站离线 Chromium 在 `480px` 容器内实测:`type="text"` 与 `type="password"` 控件高 `38px`、宽 `480px`,`rows="5"` 的 `textarea` 自动按行数撑高,高度明显大于单行输入框。
复选框(Checkbox)与单选框(Radio)
复选框允许用户从预设选项中勾选零个、一个或多个值。Bootstrap 4 使用 `.form-check` 包裹 `<label class="form-check-label">` 与 `<input type="checkbox" class="form-check-input">`,禁用项给容器加 `.disabled` 并给控件加 `disabled` 属性;在容器上追加 `.form-check-inline` 即可同行排布。实测堆叠复选框垂直错落,内联容器计算为 `display: inline-flex` 且同行对齐,勾选前两项返回 `[true, true]`,第三项保持禁用且未选中。
单选框用于从互斥选项中仅选其一,同组 `<input type="radio">` 必须共享相同的 `name` 属性。来源示例中沿用了 `.radio` 与 `.radio-inline` 写法(工程迁移提示:Bootstrap 4 官方已统一推荐改用 `.form-check` 与 `.form-check-inline` 搭配 `.form-check-input` / `.form-check-label`)。本站实测同 `name="optradio"` 组先后点选 Option 1 与 Option 2 时选中态由 `[true, false]` 互斥切换为 `[false, true]`,禁用 Option 3 无法选中,内联写法各选项保持同一水平行。
Select 下拉选择框
当需要在多个候选项中默认单选时可使用 `<select class="form-control">`(搭配 `multiple` 属性则变为列表式多选框)。本站实测单选 `<select id="sel1">` 高 `38px`、选中项 `"3"` 后 `.value` 更新为 `"3"`;多选 `<select multiple>` 高度自动大于单选框且支持同时选中 `["1", "3"]`。
离线 Chromium 实测 Input/Textarea、复选/单选堆叠与内联及 Select 单多选交互
"""Offline Playwright Chromium lab for Bootstrap 4 Chapter 24 (forms-inputs)."""
import json
from playwright.sync_api import sync_playwright
BS4_INPUTS_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; }
.form-group { margin-bottom: 1rem; width: 480px; }
.form-control {
display: block; width: 100%; height: 38px; padding: 0.375rem 0.75rem;
font-size: 1rem; line-height: 1.5; color: #495057; background-color: #fff;
border: 1px solid #ced4da; border-radius: 0.25rem;
}
textarea.form-control, select[multiple].form-control { height: auto; }
.form-check { position: relative; display: block; padding-left: 1.25rem; }
.form-check-input { position: absolute; margin-top: 0.3rem; margin-left: -1.25rem; }
.form-check-inline { display: inline-flex; align-items: center; padding-left: 0; margin-right: 0.75rem; }
.form-check-inline .form-check-input { position: static; margin-top: 0; margin-right: 0.3125rem; margin-left: 0; }
.radio { position: relative; display: block; margin-top: 0.25rem; margin-bottom: 0.25rem; }
.radio-inline { display: inline-block; padding-right: 0.75rem; vertical-align: middle; }
"""
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_INPUTS_CSS}</style></head><body>
<div class="form-group">
<label for="usr">用户名:</label>
<input type="text" class="form-control" id="usr">
</div>
<div class="form-group">
<label for="pwd">密码:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="form-group">
<label for="comment">评论:</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<div id="cb-stacked">
<div class="form-check"><label class="form-check-label"><input id="c1" type="checkbox" class="form-check-input" value="1">Option 1</label></div>
<div class="form-check"><label class="form-check-label"><input id="c2" type="checkbox" class="form-check-input" value="2">Option 2</label></div>
<div class="form-check disabled"><label class="form-check-label"><input id="c3" type="checkbox" class="form-check-input" value="3" disabled>Option 3</label></div>
</div>
<div id="cb-inline">
<div class="form-check form-check-inline"><label class="form-check-label"><input type="checkbox" class="form-check-input">Option 1</label></div>
<div class="form-check form-check-inline"><label class="form-check-label"><input type="checkbox" class="form-check-input">Option 2</label></div>
<div class="form-check form-check-inline disabled"><label class="form-check-label"><input type="checkbox" class="form-check-input" disabled>Option 3</label></div>
</div>
<div id="rd-stacked">
<div class="radio"><label><input id="r1" type="radio" name="optradio" value="1">Option 1</label></div>
<div class="radio"><label><input id="r2" type="radio" name="optradio" value="2">Option 2</label></div>
<div class="radio disabled"><label><input id="r3" type="radio" name="optradio" value="3" disabled>Option 3</label></div>
</div>
<div id="rd-inline">
<label class="radio-inline"><input type="radio" name="optinline">Option 1</label>
<label class="radio-inline"><input type="radio" name="optinline">Option 2</label>
<label class="radio-inline"><input type="radio" name="optinline" disabled>Option 3</label>
</div>
<div class="form-group">
<label for="sel1">下拉菜单:</label>
<select class="form-control" id="sel1"><option>1</option><option>2</option><option>3</option><option>4</option></select>
</div>
<div class="form-group">
<label for="sel2">多选下拉:</label>
<select multiple class="form-control" id="sel2"><option>1</option><option>2</option><option>3</option><option>4</option></select>
</div>
</body></html>""")
# Case 1: text/password inputs and textarea
actual1 = page.evaluate("""() => {
const usr = document.querySelector('#usr');
const pwd = document.querySelector('#pwd');
const ta = document.querySelector('#comment');
return {
usr_type: usr.type,
pwd_type: pwd.type,
usr_height_px: Math.round(usr.getBoundingClientRect().height),
usr_width_px: Math.round(usr.getBoundingClientRect().width),
textarea_rows: ta.rows,
textarea_taller_than_input: ta.getBoundingClientRect().height > usr.getBoundingClientRect().height,
};
}""")
expected1 = {
"usr_type": "text",
"pwd_type": "password",
"usr_height_px": 38,
"usr_width_px": 480,
"textarea_rows": 5,
"textarea_taller_than_input": True,
}
cases.append(dict(
name="input_types_and_textarea",
expected=expected1,
actual=actual1,
passed=(actual1 == expected1),
))
# Case 2: checkbox stacked & inline + multi-select + disabled
page.check("#c1")
page.check("#c2")
actual2 = page.evaluate("""() => {
const s = Array.from(document.querySelectorAll('#cb-stacked .form-check'));
const inl = Array.from(document.querySelectorAll('#cb-inline .form-check-inline'));
return {
stacked_vertical: s[1].getBoundingClientRect().top > s[0].getBoundingClientRect().top,
inline_display: getComputedStyle(inl[0]).display,
inline_same_row: Math.abs(inl[0].getBoundingClientRect().top - inl[1].getBoundingClientRect().top) <= 1,
multi_checked: [document.querySelector('#c1').checked, document.querySelector('#c2').checked],
third_disabled_unchecked: document.querySelector('#c3').disabled && !document.querySelector('#c3').checked,
};
}""")
expected2 = {
"stacked_vertical": True,
"inline_display": "inline-flex",
"inline_same_row": True,
"multi_checked": [True, True],
"third_disabled_unchecked": True,
}
cases.append(dict(
name="checkbox_stacked_and_inline",
expected=expected2,
actual=actual2,
passed=(actual2 == expected2),
))
# Case 3: radio mutual exclusion, stacked & inline
page.check("#r1")
first_pick = [page.is_checked("#r1"), page.is_checked("#r2")]
page.check("#r2")
actual3 = page.evaluate("""(firstPick) => {
const s = Array.from(document.querySelectorAll('#rd-stacked .radio'));
const inl = Array.from(document.querySelectorAll('#rd-inline .radio-inline'));
return {
first_pick: firstPick,
after_second_pick: [document.querySelector('#r1').checked, document.querySelector('#r2').checked],
third_disabled: document.querySelector('#r3').disabled,
stacked_vertical: s[1].getBoundingClientRect().top > s[0].getBoundingClientRect().top,
inline_same_row: Math.abs(inl[0].getBoundingClientRect().top - inl[1].getBoundingClientRect().top) <= 1,
};
}""", first_pick)
expected3 = {
"first_pick": [True, False],
"after_second_pick": [False, True],
"third_disabled": True,
"stacked_vertical": True,
"inline_same_row": True,
}
cases.append(dict(
name="radio_stacked_and_inline",
expected=expected3,
actual=actual3,
passed=(actual3 == expected3),
))
# Case 4: select single and multiple
page.select_option("#sel1", "3")
page.select_option("#sel2", ["1", "3"])
actual4 = page.evaluate("""() => {
const s1 = document.querySelector('#sel1');
const s2 = document.querySelector('#sel2');
return {
single_height_px: Math.round(s1.getBoundingClientRect().height),
single_value: s1.value,
multiple_selected: Array.from(s2.selectedOptions).map(o => o.value),
multiple_taller: s2.getBoundingClientRect().height > s1.getBoundingClientRect().height,
};
}""")
expected4 = {
"single_height_px": 38,
"single_value": "3",
"multiple_selected": ["1", "3"],
"multiple_taller": True,
}
cases.append(dict(
name="select_single_and_multiple",
expected=expected4,
actual=actual4,
passed=(actual4 == expected4),
))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
run()
- 核对单行输入框 38px 高度与 textarea 撑高、复选框多选及 .form-check-inline 同行、单选框同 name 互斥切换与禁用态,以及 select 单选/多选值更新。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:40853a75675161fb18d0747013e79be1c0eb2e2f98788a3eaa2ae0c3e260ed1a
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:cb7d76b68c8c5b198d24129af07ef8bee8afd48aefa8689ae1bd21a5d2f8a781
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
同组单选框为什么必须设置相同的 `name` 属性?Bootstrap 4 中 `.radio`/`.radio-inline` 建议如何升级?
展开参考解答
浏览器依靠相同的 `name` 将多个 `type="radio"` 归入同一互斥组,确保选中新项时自动取消旧项;Bootstrap 4 正式规范已用 `.form-check` 和 `.form-check-inline` 统一取代旧版 `.radio`/`.radio-inline`。