Bootstrap4 滚动监听
系统核对 Bootstrap 4 Scrollspy 滚动监听的 data-spy/data-target/data-offset 属性机制、相对定位前提、锚点匹配规则,以及水平固定导航栏与左侧垂直胶囊导航的离线 Chromium 实测。
学完这一章,你能够
- 系统核对 Bootstrap 4 Scrollspy 滚动监听的 data-spy/data-target/data-offset 属性机制、相对定位前提、锚点匹配规则,以及水平固定导航栏与左侧垂直胶囊导航的离线 Chromium 实测。
滚动监听的核心概念与水平固定导航
滚动监听(Scrollspy)用于在页面或可滚动容器发生滚动时,依据当前滚动位置自动切换对应导航项的 `.active` 高亮状态,让读者始终清楚自己正在浏览哪个内容分节。
最常见的用法是配合固定在顶部的水平导航栏(`.navbar.navbar-expand-sm.bg-dark.navbar-dark.fixed-top`)监听整个 `<body>`。本站离线 Chromium 实测(视口 `800×400`,三节内容各高 `500px`,导航栏高 `50px`,`data-offset="50"`):`body` 计算定位为 `relative`、`nav.navbar` 为 `fixed`,窗口滚动至 `0px`、`500px`、`1000px` 时高亮锚点依次自动切换为 `#section1`、`#section2` 与 `#section3`。
核心属性、偏移量与相对定位要求
启用滚动监听需先配置两个绑定属性:在被监听的可滚动容器(通常是 `<body>`,也可以是带固定高度与 `overflow-y: auto` 的独立区块)上声明 `data-spy="scroll"`,再通过 `data-target` 指定关联导航组件的选择器(如 `.navbar` 或 `#myScrollspy`),将滚动区域与导航栏建立联动。
滚动监听生效还需满足三项技术条件:第一,内容分节的 `id`(如 `<div id="section1">`)必须与导航链接的 `href`(`<a href="#section1">`)精确匹配;第二,可选属性 `data-offset` 用于设定计算当前位置时距离顶部的像素偏移,默认值为 `10px`,有顶部固定导航栏时通常按导航栏高度调大(例如 `50`);第三,声明 `data-spy="scroll"` 的元素必须设置 CSS `position: relative`。本站实测验证:当 `#section2` 顶部位于 `500px`、页面滚至 `460px` 时,`data-offset="10"`(有效位置 `470`)仍高亮 `#section1`,而 `data-offset="50"`(有效位置 `510`)提前切换至 `#section2`;在独立滚动容器中,无对应目标元素的 `#missing` 链接始终保持未激活。
垂直胶囊导航滚动监听
除顶部水平导航外,还可结合栅格系统与垂直胶囊导航(`.container-fluid > .row` 中左侧 `<nav id="myScrollspy" class="col-sm-3 col-4">` 嵌套 `<ul class="nav nav-pills flex-column">`,右侧 `.col-sm-9.col-8` 放置各节内容,并设置 `data-target="#myScrollspy"` 与 `data-offset="1"`)实现侧边目录随滚动同步高亮。本站离线 Chromium 在 `800px` 视口实测:左侧导航宽 `200px`、右侧正文宽 `600px`(`1:3` 比例),胶囊列表 `flex-direction` 为 `column`,高亮项背景色为 `rgb(0, 123, 255)`,滚动至 `0px`、`500px`、`1000px` 时激活项依次精准跟踪 `#section1` → `#section2` → `#section3`。
运行水平固定导航栏、data-offset 阈值、垂直胶囊导航与容器级滚动监听实测
"""Offline Playwright Chromium verification for Bootstrap 4 Chapter 31: Scrollspy."""
import json
import platform
from playwright.sync_api import sync_playwright
BS4_SCROLLSPY_CSS = """
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; font-family: Arial, sans-serif; }
body { position: relative; }
.navbar { display: flex; align-items: center; padding: 0 16px; height: 50px; }
.bg-dark { background-color: #343a40; }
.navbar-dark .nav-link { color: rgba(255,255,255,.5); text-decoration: none; padding: 8px 12px; display: block; }
.navbar-dark .nav-link.active { color: #ffffff; background-color: #007bff; border-radius: 4px; }
.fixed-top { position: fixed; top: 0; right: 0; left: 0; z-index: 1030; }
.navbar-nav { display: flex; list-style: none; margin: 0; padding: 0; gap: 8px; }
.container-fluid { width: 100%; padding: 0 15px; }
.row { display: flex; flex-wrap: wrap; margin: 0 -15px; }
.col-4 { flex: 0 0 33.333333%; max-width: 33.333333%; padding: 0 15px; }
.col-8 { flex: 0 0 66.666667%; max-width: 66.666667%; padding: 0 15px; }
@media (min-width: 576px) {
.col-sm-3 { flex: 0 0 25%; max-width: 25%; }
.col-sm-9 { flex: 0 0 75%; max-width: 75%; }
}
.nav { display: flex; flex-wrap: wrap; list-style: none; padding-left: 0; margin: 0; }
.flex-column { flex-direction: column; }
.nav-pills .nav-link { display: block; padding: 8px 16px; border-radius: 4px; color: #007bff; text-decoration: none; }
.nav-pills .nav-link.active { color: #ffffff; background-color: #007bff; }
#myScrollspy ul.nav-pills { position: fixed; top: 20px; width: 160px; }
.spy-section { height: 500px; padding-top: 60px; }
.spy-box { position: relative; height: 220px; overflow-y: auto; border: 1px solid #dee2e6; }
.spy-box-section { height: 220px; padding: 12px; }
"""
BS4_SCROLLSPY_JS = """
function initScrollspy(container) {
const targetSel = container.getAttribute('data-target');
const offset = parseInt(container.getAttribute('data-offset') || '10', 10);
const targetEl = document.querySelector(targetSel);
const isBody = container === document.body;
const links = Array.from(targetEl.querySelectorAll('a.nav-link[href^="#"]'));
const targets = links.map(link => {
const href = link.getAttribute('href');
const sec = document.querySelector(href);
return { link, href, sec };
}).filter(item => item.sec !== null);
function refresh() {
const scrollTop = isBody ? window.scrollY : container.scrollTop;
const pos = scrollTop + offset;
let activeItem = targets[0] || null;
for (const item of targets) {
const top = isBody ? item.sec.offsetTop : item.sec.offsetTop;
if (pos >= top) {
activeItem = item;
}
}
for (const link of links) {
link.classList.remove('active');
}
if (activeItem) {
activeItem.link.classList.add('active');
}
return activeItem ? activeItem.href : null;
}
const scroller = isBody ? window : container;
scroller.addEventListener('scroll', refresh);
refresh();
return refresh;
}
"""
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)
try:
page = browser.new_page(viewport={"width": 800, "height": 400})
# Case 1: Horizontal fixed-top navbar scrollspy
html1 = f"""<!doctype html><html><head><style>{BS4_SCROLLSPY_CSS}</style></head>
<body data-spy="scroll" data-target=".navbar" data-offset="50">
<nav class="navbar bg-dark navbar-dark fixed-top">
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link" href="#section1">Section 1</a></li>
<li class="nav-item"><a class="nav-link" href="#section2">Section 2</a></li>
<li class="nav-item"><a class="nav-link" href="#section3">Section 3</a></li>
</ul>
</nav>
<div id="section1" class="spy-section"><h1>Section 1</h1></div>
<div id="section2" class="spy-section"><h1>Section 2</h1></div>
<div id="section3" class="spy-section"><h1>Section 3</h1></div>
<script>{BS4_SCROLLSPY_JS} window.__refresh = initScrollspy(document.body);</script>
</body></html>"""
page.set_content(html1)
body_pos = page.eval_on_selector("body", "el => getComputedStyle(el).position")
nav_pos = page.eval_on_selector("nav.navbar", "el => getComputedStyle(el).position")
active_at = {}
for y in (0, 500, 1000):
page.evaluate(f"window.scrollTo(0, {y}); window.__refresh();")
active_at[str(y)] = page.eval_on_selector("a.nav-link.active", "el => el.getAttribute('href')")
exp1 = {"body_position": "relative", "nav_position": "fixed", "active_by_scrollY": {"0": "#section1", "500": "#section2", "1000": "#section3"}}
act1 = {"body_position": body_pos, "nav_position": nav_pos, "active_by_scrollY": active_at}
cases.append(dict(
name="horizontal_navbar_scrollspy",
inputs=dict(data_spy="scroll", data_target=".navbar", data_offset=50, scroll_positions=[0, 500, 1000]),
prerequisites="body 设置 position: relative 与 data-spy='scroll',fixed-top 导航栏高 50px,三个区块各高 500px",
action="在离线 Chromium 中滚动窗口至 0、500、1000px 并读取高亮的 .nav-link.active 锚点。",
expected=exp1,
actual=act1,
measurements=dict(section_tops=page.evaluate("[document.getElementById('section1').offsetTop, document.getElementById('section2').offsetTop, document.getElementById('section3').offsetTop]")),
passed=(act1 == exp1),
))
# Case 2: data-offset default 10px vs custom 50px threshold
offset_results = {}
for off in (10, 50):
html2 = html1.replace('data-offset="50"', f'data-offset="{off}"')
page.set_content(html2)
page.evaluate("window.scrollTo(0, 460); window.__refresh();")
offset_results[f"offset_{off}"] = page.eval_on_selector("a.nav-link.active", "el => el.getAttribute('href')")
exp2 = {"offset_10": "#section1", "offset_50": "#section2"}
cases.append(dict(
name="scrollspy_offset_threshold",
inputs=dict(scrollY=460, section2_top=500, offsets=[10, 50]),
prerequisites="section2 顶部位于 500px,分别配置默认 data-offset='10' 与 data-offset='50'",
action="将页面滚动至 460px,对比两种 data-offset 下是否提前激活 #section2。",
expected=exp2,
actual=offset_results,
measurements=dict(effective_pos_10=470, effective_pos_50=510),
passed=(offset_results == exp2),
))
# Case 3: Vertical pills scrollspy
html3 = f"""<!doctype html><html><head><style>{BS4_SCROLLSPY_CSS}</style></head>
<body data-spy="scroll" data-target="#myScrollspy" data-offset="1">
<div class="container-fluid">
<div class="row">
<nav class="col-sm-3 col-4" id="myScrollspy">
<ul class="nav nav-pills flex-column">
<li class="nav-item"><a class="nav-link active" href="#section1">Section 1</a></li>
<li class="nav-item"><a class="nav-link" href="#section2">Section 2</a></li>
<li class="nav-item"><a class="nav-link" href="#section3">Section 3</a></li>
</ul>
</nav>
<div class="col-sm-9 col-8" id="contentCol">
<div id="section1" class="spy-section"><h1>Section 1</h1></div>
<div id="section2" class="spy-section"><h1>Section 2</h1></div>
<div id="section3" class="spy-section"><h1>Section 3</h1></div>
</div>
</div>
</div>
<script>{BS4_SCROLLSPY_JS} window.__refresh = initScrollspy(document.body);</script>
</body></html>"""
page.set_content(html3)
ul_dir = page.eval_on_selector("#myScrollspy ul.nav-pills", "el => getComputedStyle(el).flexDirection")
nav_w = round(page.eval_on_selector("#myScrollspy", "el => el.getBoundingClientRect().width"))
col_w = round(page.eval_on_selector("#contentCol", "el => el.getBoundingClientRect().width"))
v_active = {}
for y in (0, 500, 1000):
page.evaluate(f"window.scrollTo(0, {y}); window.__refresh();")
v_active[str(y)] = page.eval_on_selector("#myScrollspy a.nav-link.active", "el => el.getAttribute('href')")
active_bg = page.eval_on_selector("#myScrollspy a.nav-link.active", "el => getComputedStyle(el).backgroundColor")
exp3 = {
"pills_flex_direction": "column",
"nav_width_px": 200,
"content_width_px": 600,
"active_bg": "rgb(0, 123, 255)",
"active_by_scrollY": {"0": "#section1", "500": "#section2", "1000": "#section3"},
}
act3 = {
"pills_flex_direction": ul_dir,
"nav_width_px": nav_w,
"content_width_px": col_w,
"active_bg": active_bg,
"active_by_scrollY": v_active,
}
cases.append(dict(
name="vertical_pills_scrollspy",
inputs=dict(viewport_width=800, data_target="#myScrollspy", data_offset=1),
prerequisites="左侧 nav.col-sm-3 使用 .nav.nav-pills.flex-column,右侧 .col-sm-9 承载三节内容",
action="在 800px 视口验证左右 1:3 宽度分配、垂直方向及滚动切换 #section1/#section2/#section3 高亮状态。",
expected=exp3,
actual=act3,
measurements=dict(ratio=round(col_w / nav_w, 2)),
passed=(act3 == exp3),
))
# Case 4: Container-level relative positioning & href/id matching validation
html4 = f"""<!doctype html><html><head><style>{BS4_SCROLLSPY_CSS}</style></head>
<body>
<nav id="boxNav" class="navbar bg-dark navbar-dark">
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link" href="#box1">Box 1</a></li>
<li class="nav-item"><a class="nav-link" href="#box2">Box 2</a></li>
<li class="nav-item"><a class="nav-link" href="#missing">Missing</a></li>
</ul>
</nav>
<div id="scrollBox" class="spy-box" data-spy="scroll" data-target="#boxNav" data-offset="10">
<div id="box1" class="spy-box-section">Box 1</div>
<div id="box2" class="spy-box-section">Box 2</div>
</div>
<script>{BS4_SCROLLSPY_JS} window.__refreshBox = initScrollspy(document.getElementById('scrollBox'));</script>
</body></html>"""
page.set_content(html4)
box_pos = page.eval_on_selector("#scrollBox", "el => getComputedStyle(el).position")
page.evaluate("const b = document.getElementById('scrollBox'); b.scrollTop = 215; window.__refreshBox();")
box_active = page.eval_on_selector("#boxNav a.nav-link.active", "el => el.getAttribute('href')")
missing_active = page.eval_on_selector("#boxNav a[href='#missing']", "el => el.classList.contains('active')")
exp4 = {"container_position": "relative", "active_href": "#box2", "missing_link_active": False}
act4 = {"container_position": box_pos, "active_href": box_active, "missing_link_active": missing_active}
cases.append(dict(
name="relative_position_and_id_matching",
inputs=dict(container_scrollTop=215, data_offset=10, links=["#box1", "#box2", "#missing"]),
prerequisites="独立滚动容器 #scrollBox 具备 position: relative 与 overflow-y: auto,导航含未匹配锚点 #missing",
action="将容器滚至 215px,核对有效匹配锚点 #box2 激活而无对应元素的 #missing 保持未激活。",
expected=exp4,
actual=act4,
measurements=dict(box2_offsetTop=page.eval_on_selector("#box2", "el => el.offsetTop")),
passed=(act4 == exp4),
))
finally:
browser.close()
print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对水平固定导航栏在 scrollY=0/500/1000 依次高亮 #section1/#section2/#section3、scrollY=460 时 data-offset=10 与 50 产生不同高亮阈值、垂直胶囊 200px/600px 布局与 rgb(0, 123, 255) 高亮,以及独立容器 position: relative 与未匹配锚点隔离。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:cf33e379a0aadd926574cc6c3312afde35b31f6b4b67f12560c043c34c591f02
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:725a6aef389e92f4572da275042de7e002ca5d17bd848c8ac1959ebea143a79f
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在顶部使用 `fixed-top` 导航栏配合 Scrollspy 时,为什么要调整 `data-offset` 且要求监听容器设置 `position: relative`?
展开参考解答
`fixed-top` 导航栏会遮挡视口顶部约 50px 区域,使用默认 `data-offset="10"` 会导致分节标题刚进入可视区下方时导航高亮滞后,将 `data-offset` 设为与导航栏高度接近的值(如 50)可让切换时机与视觉位置对齐;同时监听容器需设为 `position: relative`,确保子分节的 `offsetTop` 均以该滚动容器为定位基准正确计算。