Bootstrap5 下拉菜单
讲解 Bootstrap 5 下拉选择框 `.form-select` 的单选与多选模式、三档尺寸变体、禁用状态以及配合 `<datalist>` 的可输入候选数据列表,并附无头 Chromium 实测数据。
学完这一章,你能够
- 讲解 Bootstrap 5 下拉选择框 `.form-select` 的单选与多选模式、三档尺寸变体、禁用状态以及配合 `<datalist>` 的可输入候选数据列表,并附无头 Chromium 实测数据。
单选、多选与 .form-select 渲染
HTML 原生 `<select>` 可表现为单选下拉框,或在添加 `multiple` 属性后展开为支持多选的列表框。在 Bootstrap 5 中,统一为 `<select>` 添加 `.form-select` 类替代旧版的 `.custom-select`,通过 `appearance: none` 重置浏览器默认外观并呈现 100% 宽度的统一风格。本站离线 Chromium 在 600px 外框实测:单选 `.form-select` 宽 `600px`、`appearance: none`,切换选中值为 `"3"`;多选 `<select multiple class="form-select">` 可同时选中 `["2", "4"]` 且渲染高度大于单选框。
尺寸变体与禁用状态
与输入框一致,下拉框通过组合 `.form-select-lg` 与 `.form-select-sm` 调整大小。Chromium 实测三档选择框字号依次为 `20px`、`16px`、`14px`,渲染高度依次为 `48px`、`38px`、`31px`,与对应尺寸的 `.form-control` 保持高度一致,便于同行混排。
为 `<select class="form-select">` 添加 `disabled` 属性即可禁用下拉选择。实测其 `disabled` DOM 属性为 `true`,计算背景色切换为浅灰 `rgb(233, 236, 239)`,保持初始默认选项不可交互。
数据列表(datalist)
若既要提供预设候选项又希望允许用户自由输入,可结合 `<input class="form-control" list="sites">` 与同 `id` 的 `<datalist id="sites">` 及其 `<option value="...">` 项(注意 `<label for="...">` 应指向输入框自身的 `id` 以保证点击聚焦)。本站 Chromium 实测:输入框 `el.list.id` 正确关联 `"sites"` 并暴露 5 个候选项,既可填入预设项 `"MDN"`,也可接受列表之外的自定义文本 `"CustomSite"`。
运行 Bootstrap 5 下拉框单选/多选、尺寸、禁用与 datalist 实验
"""Offline Playwright Chromium verification for Bootstrap 5 Form Select & Datalist."""
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; }
.wrap { width: 600px; }
.form-label { display: inline-block; margin-bottom: 0.5rem; }
.form-select {
display: block; width: 100%; padding: 0.375rem 2.25rem 0.375rem 0.75rem;
font-size: 1rem; font-weight: 400; line-height: 1.5; color: #212529;
background-color: #fff; border: 1px solid #ced4da; border-radius: 0.375rem;
appearance: none;
}
.form-select:disabled { background-color: #e9ecef; }
.form-select-lg { padding-top: 0.5rem; padding-bottom: 0.5rem; padding-left: 1rem; font-size: 1.25rem; border-radius: 0.5rem; }
.form-select-sm { padding-top: 0.25rem; padding-bottom: 0.25rem; padding-left: 0.5rem; font-size: 0.875rem; border-radius: 0.25rem; }
.form-control {
display: block; width: 100%; padding: 0.375rem 0.75rem;
font-size: 1rem; line-height: 1.5; color: #212529;
background-color: #fff; border: 1px solid #ced4da; border-radius: 0.375rem;
}
"""
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": 700})
# Case 1: single vs multiple form-select
page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
<div class="wrap">
<select id="single" class="form-select">
<option value="1">1</option><option value="2">2</option>
<option value="3">3</option><option value="4">4</option>
</select>
<select id="multi" multiple class="form-select">
<option value="1">1</option><option value="2">2</option>
<option value="3">3</option><option value="4">4</option>
</select>
</div></body></html>""")
page.select_option("#single", "3")
page.select_option("#multi", ["2", "4"])
act1 = page.evaluate("""() => {
const s = document.getElementById('single');
const m = document.getElementById('multi');
return {
single_width: Math.round(s.getBoundingClientRect().width),
single_appearance: getComputedStyle(s).appearance,
single_value: s.value,
multi_selected: Array.from(m.selectedOptions).map(o => o.value),
multi_taller_than_single: m.getBoundingClientRect().height > s.getBoundingClientRect().height,
};
}""")
exp1 = {
"single_width": 600,
"single_appearance": "none",
"single_value": "3",
"multi_selected": ["2", "4"],
"multi_taller_than_single": True,
}
cases.append({"name": "select_single_and_multiple", "expected": exp1, "actual": act1, "passed": act1 == exp1})
# Case 2: form-select-lg / default / form-select-sm
page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
<div class="wrap">
<select id="slg" class="form-select form-select-lg"><option>1</option></select>
<select id="smd" class="form-select"><option>1</option></select>
<select id="ssm" class="form-select form-select-sm"><option>1</option></select>
</div></body></html>""")
act2 = page.evaluate("""() => {
const cs = id => getComputedStyle(document.getElementById(id));
const h = id => Math.round(document.getElementById(id).getBoundingClientRect().height);
return {
font_sizes: [cs('slg').fontSize, cs('smd').fontSize, cs('ssm').fontSize],
heights_px: [h('slg'), h('smd'), h('ssm')],
strict_order: h('slg') > h('smd') && h('smd') > h('ssm'),
};
}""")
exp2 = {
"font_sizes": ["20px", "16px", "14px"],
"heights_px": [48, 38, 31],
"strict_order": True,
}
cases.append({"name": "select_sizing_variants", "expected": exp2, "actual": act2, "passed": act2 == exp2})
# Case 3: disabled select
page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
<div class="wrap">
<select id="sdis" class="form-select" disabled>
<option value="1">1</option><option value="2">2</option>
</select>
</div></body></html>""")
act3 = page.evaluate("""() => {
const el = document.getElementById('sdis');
return {
disabled: el.disabled,
bg: getComputedStyle(el).backgroundColor,
value: el.value,
};
}""")
exp3 = {"disabled": True, "bg": "rgb(233, 236, 239)", "value": "1"}
cases.append({"name": "select_disabled_state", "expected": exp3, "actual": act3, "passed": act3 == exp3})
# Case 4: datalist input
page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
<div class="wrap">
<label for="site" class="form-label">选择站点:</label>
<input class="form-control" list="sites" name="site" id="site">
<datalist id="sites">
<option value="MDN"></option>
<option value="Bootstrap"></option>
<option value="GitHub"></option>
<option value="Wikipedia"></option>
<option value="W3C"></option>
</datalist>
</div></body></html>""")
page.fill("#site", "MDN")
val_preset = page.input_value("#site")
page.fill("#site", "CustomSite")
act4 = page.evaluate("""(valPreset) => {
const el = document.getElementById('site');
return {
list_id: el.list ? el.list.id : null,
option_count: el.list ? el.list.options.length : 0,
preset_val: valPreset,
custom_val: el.value,
};
}""", val_preset)
exp4 = {"list_id": "sites", "option_count": 5, "preset_val": "MDN", "custom_val": "CustomSite"}
cases.append({"name": "input_datalist_binding", "expected": exp4, "actual": act4, "passed": act4 == exp4})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 .form-select 600px 全宽与 multiple 多选 ['2', '4']、lg/默认/sm 字号(20/16/14px)与高度(48/38/31px)、disabled 浅灰背景以及 input+datalist 5 项关联与自由输入。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:a9236d910edb45d790346d6bb55e71ca597dc62ac57faa1e300bb2af0fd7d131
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:9e27eee7f36705bbbe073e7202ef1e3fef578712170b26f2341ca8d64035f23a
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`<select class="form-select">` 与 `<input class="form-control" list="...">` 搭配 `<datalist>` 在交互约束上有何不同?
展开参考解答
`<select>` 严格限定用户只能从预设 `<option>` 中单选或多选;`<datalist>` 仅向 `<input>` 提供自动补全候选建议,用户仍可键入并提交列表之外的任意自定义值。