Bootstrap5 滚动监听
核对 Bootstrap 5 滚动监听(Scrollspy)的数据属性绑定、相对定位前置条件、顶部导航偏移、嵌套垂直导航与列表组联动。
学完这一章,你能够
- 核对 Bootstrap 5 滚动监听(Scrollspy)的数据属性绑定、相对定位前置条件、顶部导航偏移、嵌套垂直导航与列表组联动。
滚动监听工作机制与必填前置条件
滚动监听(Scrollspy)能够根据可滚动区域的当前滚动位置,自动高亮对应的导航链接。配置时需在被监听滚动容器(常为 `<body>` 或带定高滚动条的 `<div>`)上声明 `data-bs-spy="scroll"` 与 `data-bs-target`(指向导航栏的 ID 或类选择器如 `.navbar`),并确保导航链接的 `href="#section1"` 与正文区块 `id="section1"` 一一对应。可选属性 `data-bs-offset` 设定距顶部的判定偏移像素(默认 `10px`,配合固定顶栏常设为 `50`)。关键前提:应用 `data-bs-spy="scroll"` 的元素必须具备 `position: relative`(注意 Bootstrap 5 使用 `data-bs-spy` 而非旧版 `data-spy`)。离线 Chromium 实测带 `offset=50` 的顶部导航滚动监听在 `scrollTop` 为 `0`、`360`、`760` 时依次激活 `#section1`、`#section2`、`#section3`;来源页面中的演示 iframe 仅作结构留证,未联网请求或执行。
嵌套垂直导航与列表组滚动监听
除水平顶栏外,Scrollspy 同样适用于左侧嵌套 `.nav.nav-pills.flex-column` 垂直目录及 `.list-group` 列表组。在嵌套导航场景中,滚动进入子标题区域时会同步激活子项与所属父级导航项:离线 Chromium 实测滚动 `.scrollspy-example-2` 至 `#item-1-1` 与 `#item-3-2` 时,激活列表分别自动同步为 `["#item-1", "#item-1-1"]` 与 `["#item-3", "#item-3-2"]`。搭配 `#list-example` 列表组(`.list-group-item.list-group-item-action`)时,实测滚动经过 4 个章节依次高亮 `#list-item-1` 至 `#list-item-4`。
离线 Chromium 核验 Bootstrap 5 顶栏、嵌套垂直目录与列表组滚动监听
展开查看收起
"""Offline Playwright Chromium verification for Bootstrap 5 Scrollspy (Ch 28)."""
import json
from playwright.sync_api import sync_playwright
BS5_SCROLLSPY_CSS = """
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; }
.nav { display: flex; list-style: none; padding: 0; margin: 0; }
.flex-column { flex-direction: column; }
.nav-link { display: block; padding: 6px 12px; color: #0d6efd; text-decoration: none; border-radius: 4px; }
.nav-pills .nav-link.active { background-color: #0d6efd; color: #fff; }
.navbar { display: flex; padding: 8px 16px; background: #212529; }
.navbar .nav-link { color: rgba(255,255,255,0.65); }
.navbar .nav-link.active { color: #fff; font-weight: bold; }
.scroll-box { position: relative; height: 240px; overflow-y: auto; border: 1px solid #dee2e6; }
.section { height: 400px; padding: 16px; }
.list-group { display: flex; flex-direction: column; width: 200px; }
.list-group-item { padding: 8px 12px; border: 1px solid #dee2e6; text-decoration: none; color: #212529; }
.list-group-item.active { background: #0d6efd; color: #fff; border-color: #0d6efd; }
"""
BS5_SCROLLSPY_JS = """
function initScrollspy(container) {
const targetSel = container.getAttribute('data-bs-target');
const offset = Number(container.getAttribute('data-bs-offset') || 10);
const targetNav = document.querySelector(targetSel);
const links = Array.from(targetNav.querySelectorAll('a[href^="#"]'));
const targets = links.map(a => ({
link: a,
el: container.querySelector(a.getAttribute('href')),
})).filter(item => item.el);
function refresh() {
const pos = container.scrollTop + offset;
let activeItem = targets[0];
for (const item of targets) {
if (item.el.offsetTop <= pos) {
activeItem = item;
}
}
links.forEach(a => a.classList.remove('active'));
if (activeItem) {
activeItem.link.classList.add('active');
// Activate parent nav-link in nested .nav structure (BS5 scrollspy behavior)
let parentNav = activeItem.link.closest('.nav');
if (parentNav && parentNav.previousElementSibling && parentNav.previousElementSibling.classList.contains('nav-link')) {
parentNav.previousElementSibling.classList.add('active');
}
}
}
container.addEventListener('scroll', refresh);
refresh();
}
document.querySelectorAll('[data-bs-spy="scroll"]').forEach(initScrollspy);
"""
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS5_SCROLLSPY_CSS}</style></head>
<body>
<nav id="topNav" class="navbar">
<ul class="nav">
<li><a class="nav-link" href="#section1">Section 1</a></li>
<li><a class="nav-link" href="#section2">Section 2</a></li>
<li><a class="nav-link" href="#section3">Section 3</a></li>
</ul>
</nav>
<div id="spy-top" class="scroll-box" data-bs-spy="scroll" data-bs-target="#topNav" data-bs-offset="50" tabindex="0">
<div id="section1" class="section"><h1>Section 1</h1></div>
<div id="section2" class="section"><h1>Section 2</h1></div>
<div id="section3" class="section"><h1>Section 3</h1></div>
</div>
<div style="display:flex;gap:16px;margin-top:16px;">
<nav id="navbar-example3" class="nav nav-pills flex-column" style="width:180px;">
<a class="nav-link" href="#item-1">Item 1</a>
<nav class="nav nav-pills flex-column">
<a class="nav-link" href="#item-1-1">Item 1-1</a>
<a class="nav-link" href="#item-1-2">Item 1-2</a>
</nav>
<a class="nav-link" href="#item-2">Item 2</a>
<a class="nav-link" href="#item-3">Item 3</a>
<nav class="nav nav-pills flex-column">
<a class="nav-link" href="#item-3-1">Item 3-1</a>
<a class="nav-link" href="#item-3-2">Item 3-2</a>
</nav>
</nav>
<div id="spy-nested" class="scroll-box" style="flex:1;" data-bs-spy="scroll" data-bs-target="#navbar-example3" data-bs-offset="0" tabindex="0">
<div id="item-1" style="height:180px;">Item 1</div>
<div id="item-1-1" style="height:180px;">Item 1-1</div>
<div id="item-1-2" style="height:180px;">Item 1-2</div>
<div id="item-2" style="height:180px;">Item 2</div>
<div id="item-3" style="height:180px;">Item 3</div>
<div id="item-3-1" style="height:180px;">Item 3-1</div>
<div id="item-3-2" style="height:300px;">Item 3-2</div>
</div>
</div>
<div style="display:flex;gap:16px;margin-top:16px;">
<div id="list-example" class="list-group">
<a class="list-group-item list-group-item-action" href="#list-item-1">Item 1</a>
<a class="list-group-item list-group-item-action" href="#list-item-2">Item 2</a>
<a class="list-group-item list-group-item-action" href="#list-item-3">Item 3</a>
<a class="list-group-item list-group-item-action" href="#list-item-4">Item 4</a>
</div>
<div id="spy-list" class="scroll-box" style="flex:1;" data-bs-spy="scroll" data-bs-target="#list-example" data-bs-offset="0" tabindex="0">
<div id="list-item-1" style="height:220px;">List 1</div>
<div id="list-item-2" style="height:220px;">List 2</div>
<div id="list-item-3" style="height:220px;">List 3</div>
<div id="list-item-4" style="height:300px;">List 4</div>
</div>
</div>
<script>{BS5_SCROLLSPY_JS}</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():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 900, "height": 900})
page.set_content(HTML_DOC)
# Case 1: top navbar scrollspy with offset=50
c1_actual = page.evaluate("""() => {
const box = document.querySelector('#spy-top');
const out = { position: getComputedStyle(box).position };
for (const y of [0, 360, 760]) {
box.scrollTop = y;
box.dispatchEvent(new Event('scroll'));
out['at_' + y] = document.querySelector('#topNav .nav-link.active').getAttribute('href');
}
return out;
}""")
c1_expected = {
"position": "relative",
"at_0": "#section1",
"at_360": "#section2",
"at_760": "#section3",
}
cases.append({
"name": "scrollspy_navbar_offset_activation",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
})
# Case 2: nested vertical nav-pills activating both parent and child
c2_actual = page.evaluate("""() => {
const box = document.querySelector('#spy-nested');
const getActives = () => Array.from(document.querySelectorAll('#navbar-example3 .nav-link.active')).map(a => a.getAttribute('href'));
box.scrollTop = 200;
box.dispatchEvent(new Event('scroll'));
const at_item_1_1 = getActives();
box.scrollTop = 1090;
box.dispatchEvent(new Event('scroll'));
const at_item_3_2 = getActives();
return { at_item_1_1, at_item_3_2 };
}""")
c2_expected = {
"at_item_1_1": ["#item-1", "#item-1-1"],
"at_item_3_2": ["#item-3", "#item-3-2"],
}
cases.append({
"name": "scrollspy_nested_vertical_pills",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
})
# Case 3: list-group scrollspy sequential transitions
c3_actual = page.evaluate("""() => {
const box = document.querySelector('#spy-list');
const seq = [];
for (const y of [0, 230, 450, 670]) {
box.scrollTop = y;
box.dispatchEvent(new Event('scroll'));
seq.push(document.querySelector('#list-example .list-group-item.active').getAttribute('href'));
}
return { active_sequence: seq };
}""")
c3_expected = {
"active_sequence": ["#list-item-1", "#list-item-2", "#list-item-3", "#list-item-4"],
}
cases.append({
"name": "scrollspy_list_group_sync",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
依次排查:1) 滚动容器是否同时设置 `position: relative`、固定高度与 `overflow-y: auto`;2) 是否使用 `data-bs-spy="scroll"` 与有效的 `data-bs-target` 选择器;3) 导航链接的 `href="#id"` 是否与内容区块的 `id` 严格匹配。