Bootstrap5 下拉菜单
核对 Bootstrap 5 data-bs-toggle 下拉切换、标题/分割线/状态项、dropend/dropstart/dropup 方向与右缘对齐、按钮组嵌套及深色过滤菜单。
学完这一章,你能够
- 核对 Bootstrap 5 data-bs-toggle 下拉切换、标题/分割线/状态项、dropend/dropstart/dropup 方向与右缘对齐、按钮组嵌套及深色过滤菜单。
基础下拉菜单结构与 BS5 属性规范
下拉菜单(Dropdown)是可切换展开/收起的上下文链接列表。容器使用 `.dropdown`,触发按钮或链接需添加 `.dropdown-toggle` 与 Bootstrap 5 的 `data-bs-toggle="dropdown"`(取代 Bootstrap 4 的 `data-toggle="dropdown"`),菜单列表容器使用 `.dropdown-menu`,内部每一项添加 `.dropdown-item`。本站离线 Chromium 实测初始菜单为 `display: none`,点击触发按钮后切换为 `block` 且 `aria-expanded` 更新为 `"true"`。
分割线、分组标题、状态项与纯文本项
在菜单中使用 `<hr class="dropdown-divider">`(HTML5 空元素无需闭合标签)可绘制 `1px` 水平分割线,使用 `.dropdown-header` 可插入 `14px` 弱化灰色分组标题。
菜单项支持 `.active` 高亮(实测蓝底 `rgb(13, 110, 253)`)与 `.disabled` 禁用(`pointer-events: none`);若需在菜单内放置非按钮静态说明文字,则使用 `.dropdown-item-text`(`display: block` 保持与菜单项一致的内边距)。
弹出方向与右缘对齐(BS5 命名迁移)
Bootstrap 5 按逻辑书写方向将 Bootstrap 4 的 `.dropright`/`.dropleft` 重命名为 `.dropend`/`.dropstart`,并明确区分“弹出方向”与“菜单对齐”两个维度:弹出方向由外层容器控制(默认向下 `.dropdown`,向右 `.dropend`,向左 `.dropstart`,向上 `.dropup`),而右缘对齐则将 `.dropdown-menu-end` 添加在 `.dropdown-menu` 元素本身上。
本站离线 Chromium 逐项核验了四类几何定位:`.dropend` 展开菜单左缘紧邻按钮右缘(向右弹出);`.dropstart` 展开菜单右缘紧邻按钮左缘(向左弹出,注意不要误写成向上);`.dropup` 展开菜单底缘紧邻按钮顶缘(向上弹出);`.dropdown-menu.dropdown-menu-end` 的菜单右缘与触发按钮右缘对齐(误差 `<= 1px`)。
按钮组嵌套与过滤型深色菜单案例
下拉菜单可直接嵌入水平 `.btn-group` 或垂直 `.btn-group-vertical` 的子 `.btn-group` 容器中,实测点击 `Sony` 后展开 `Tablet` 与 `Smartphone` 两项。
在导航栏或高级操作面板中,还可使用 `.dropdown-menu-dark`(深灰背景 `rgb(52, 58, 64)`)并在菜单顶部嵌入搜索框实现即时过滤。实测输入 `"Sep"` 后可见菜单项由 4 条实时筛选为 1 条 `"Separated link"`。
在离线 Chromium 中验证下拉菜单切换、四向定位/右缘对齐、按钮组嵌套及深色过滤交互
展开查看收起
"""Offline Playwright Chromium verification for Bootstrap 5 Dropdowns (Ch 19)."""
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: 80px 240px; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; line-height: 1.5; }
.btn {
display: inline-block; padding: 0.375rem 0.75rem; font-size: 1rem; line-height: 1.5;
border: 1px solid transparent; border-radius: 0.375rem; cursor: pointer;
}
.btn-primary { color: #fff; background-color: #0d6efd; border-color: #0d6efd; }
.dropdown, .dropup, .dropend, .dropstart, .btn-group, .btn-group-vertical { position: relative; display: inline-flex; }
.btn-group-vertical { flex-direction: column; }
.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; font-size: 1rem; color: #212529;
list-style: none; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.175);
border-radius: 0.375rem;
}
.dropdown-menu.show { display: block; }
.dropdown-menu-end { right: 0; left: auto; }
.dropup > .dropdown-menu { top: auto; bottom: 100%; margin: 0 0 0.125rem 0; }
.dropend > .dropdown-menu { top: 0; right: auto; left: 100%; margin: 0 0 0 0.125rem; }
.dropstart > .dropdown-menu { top: 0; right: 100%; left: auto; margin: 0 0.125rem 0 0; }
.dropdown-item {
display: block; width: 100%; padding: 0.25rem 1rem; color: #212529; text-decoration: none; white-space: nowrap;
}
.dropdown-item.active { color: #fff; background-color: #0d6efd; }
.dropdown-item.disabled { color: #adb5bd; pointer-events: none; background-color: transparent; }
.dropdown-item-text { display: block; padding: 0.25rem 1rem; color: #212529; }
.dropdown-divider { height: 0; margin: 0.5rem 0; overflow: hidden; border: 0; border-top: 1px solid rgba(0, 0, 0, 0.175); }
.dropdown-header { display: block; padding: 0.5rem 1rem; margin: 0; font-size: 0.875rem; color: #6c757d; white-space: nowrap; }
.dropdown-menu-dark { color: #dee2e6; background-color: #343a40; border-color: rgba(0, 0, 0, 0.15); }
.dropdown-menu-dark .dropdown-item { color: #dee2e6; }
.row-gap { margin-bottom: 40px; }
</style>
</head>
<body>
<div class="row-gap">
<div id="dd-basic" class="dropdown">
<button id="btn-basic" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">下拉菜单按钮</button>
<ul id="menu-basic" class="dropdown-menu">
<li><h5 id="dd-hdr" class="dropdown-header">标题 1</h5></li>
<li><a id="dd-normal" class="dropdown-item" href="#">常规项</a></li>
<li><a id="dd-active" class="dropdown-item active" href="#">激活项</a></li>
<li><a id="dd-disabled" class="dropdown-item disabled" href="#">禁用项</a></li>
<li><hr id="dd-div" class="dropdown-divider"></li>
<li><span id="dd-txt" class="dropdown-item-text">仅仅是文本</span></li>
</ul>
</div>
</div>
<div class="row-gap">
<div id="dd-end" class="dropend">
<button id="btn-end" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Dropend</button>
<ul id="menu-end" class="dropdown-menu show"><li><a class="dropdown-item" href="#">向右展开</a></li></ul>
</div>
</div>
<div class="row-gap">
<div id="dd-start" class="dropstart">
<button id="btn-start" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Dropstart</button>
<ul id="menu-start" class="dropdown-menu show"><li><a class="dropdown-item" href="#">向左展开</a></li></ul>
</div>
</div>
<div class="row-gap">
<div id="dd-up" class="dropup">
<button id="btn-up" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Dropup</button>
<ul id="menu-up" class="dropdown-menu show"><li><a class="dropdown-item" href="#">向上展开</a></li></ul>
</div>
</div>
<div class="row-gap">
<div id="dd-align-end" class="dropdown">
<button id="btn-align-end" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">右缘对齐按钮较宽</button>
<ul id="menu-align-end" class="dropdown-menu dropdown-menu-end show"><li><a class="dropdown-item" href="#">右对齐项</a></li></ul>
</div>
</div>
<div class="row-gap">
<div class="btn-group">
<button type="button" class="btn btn-primary">Apple</button>
<div class="btn-group">
<button id="grp-dd-btn" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">Sony</button>
<ul id="grp-dd-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>
</div>
<div class="row-gap">
<div id="filter-dark" class="dropdown-menu dropdown-menu-dark show" style="position:static">
<input id="filter-input" type="search" placeholder="Type to filter...">
<ul id="filter-list" style="list-style:none;padding:0;margin:4px 0 0 0">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
<li><a class="dropdown-item" href="#">Separated link</a></li>
</ul>
</div>
</div>
<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));
});
});
document.getElementById("filter-input").addEventListener("input", e => {
const q = e.target.value.toLowerCase();
document.querySelectorAll("#filter-list li").forEach(li => {
li.style.display = li.textContent.toLowerCase().includes(q) ? "" : "none";
});
});
</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": 1000})
page.set_content(HTML, wait_until="load")
before = page.evaluate('getComputedStyle(document.getElementById("menu-basic")).display')
page.click("#btn-basic")
c1_actual = page.evaluate("""(before) => {
const m = getComputedStyle(document.getElementById("menu-basic"));
const hdr = getComputedStyle(document.getElementById("dd-hdr"));
const act = getComputedStyle(document.getElementById("dd-active"));
const dis = getComputedStyle(document.getElementById("dd-disabled"));
const div = getComputedStyle(document.getElementById("dd-div"));
const txt = getComputedStyle(document.getElementById("dd-txt"));
return {
initial_display: before,
opened_display: m.display,
aria_expanded: document.getElementById("btn-basic").getAttribute("aria-expanded"),
header_font_size: hdr.fontSize,
active_bg: act.backgroundColor,
disabled_pointer_events: dis.pointerEvents,
divider_border_top: div.borderTopWidth,
item_text_display: txt.display,
};
}""", before)
c1_expected = {
"initial_display": "none",
"opened_display": "block",
"aria_expanded": "true",
"header_font_size": "14px",
"active_bg": "rgb(13, 110, 253)",
"disabled_pointer_events": "none",
"divider_border_top": "1px",
"item_text_display": "block",
}
c2_actual = page.evaluate("""() => {
const bEnd = document.getElementById("btn-end").getBoundingClientRect();
const mEnd = document.getElementById("menu-end").getBoundingClientRect();
const bStart = document.getElementById("btn-start").getBoundingClientRect();
const mStart = document.getElementById("menu-start").getBoundingClientRect();
const bUp = document.getElementById("btn-up").getBoundingClientRect();
const mUp = document.getElementById("menu-up").getBoundingClientRect();
const bAe = document.getElementById("btn-align-end").getBoundingClientRect();
const mAe = document.getElementById("menu-align-end").getBoundingClientRect();
return {
dropend_opens_right: mEnd.left >= bEnd.right - 1,
dropstart_opens_left: mStart.right <= bStart.left + 1,
dropup_opens_above: mUp.bottom <= bUp.top + 1,
menu_end_aligns_right_edge: Math.abs(mAe.right - bAe.right) <= 1,
};
}""")
c2_expected = {
"dropend_opens_right": True,
"dropstart_opens_left": True,
"dropup_opens_above": True,
"menu_end_aligns_right_edge": True,
}
page.click("#grp-dd-btn")
c3_actual = page.evaluate("""() => ({
grp_menu_display: getComputedStyle(document.getElementById("grp-dd-menu")).display,
grp_expanded: document.getElementById("grp-dd-btn").getAttribute("aria-expanded"),
grp_item_texts: Array.from(document.querySelectorAll("#grp-dd-menu .dropdown-item")).map(a => a.textContent),
})""")
c3_expected = {
"grp_menu_display": "block",
"grp_expanded": "true",
"grp_item_texts": ["Tablet", "Smartphone"],
}
page.fill("#filter-input", "Sep")
c4_actual = page.evaluate("""() => {
const visible = Array.from(document.querySelectorAll("#filter-list li"))
.filter(li => getComputedStyle(li).display !== "none")
.map(li => li.textContent.trim());
return {
dark_bg: getComputedStyle(document.getElementById("filter-dark")).backgroundColor,
filtered_visible_items: visible,
};
}""")
c4_expected = {
"dark_bg": "rgb(52, 58, 64)",
"filtered_visible_items": ["Separated link"],
}
browser.close()
cases = [
dict(name="dropdown_toggle_divider_header_states", description="核对 data-bs-toggle=dropdown 切换、标题/分割线/激活/禁用与文本项", expected=c1_expected, actual=c1_actual, passed=c1_actual == c1_expected),
dict(name="dropdown_directions_and_alignment", description="核对 BS5 .dropend/.dropstart/.dropup 弹出方向与 .dropdown-menu-end 右缘对齐", expected=c2_expected, actual=c2_actual, passed=c2_actual == c2_expected),
dict(name="dropdown_in_button_groups", description="核对按钮组嵌套下拉菜单点击展开与选项数量", expected=c3_expected, actual=c3_actual, passed=c3_actual == c3_expected),
dict(name="filterable_dropdown_light_and_dark", description="核对深色主题 .dropdown-menu-dark 与输入过滤交互筛选", 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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`.dropend` 挂在外层下拉容器上,使菜单从按钮右侧横向弹出(替代 BS4 `.dropright`);`.dropdown-menu-end` 挂在 `.dropdown-menu` 元素本身上,用于让向下弹出的菜单右缘与触发按钮右缘对齐。