工作原理
当锚点 href 引用的 id 元素滚动进入视图时,滚动监听会切换锚点(<a>)元素上的 .active 类。滚动监听最好与 Bootstrap 的导航组件或列表组配合使用,但它也可用于当前页面中的任何锚点元素。工作原理如下。
-
首先,滚动监听需要两样东西:导航、列表组或一组简单的链接,以及一个可滚动容器。可滚动容器可以是
<body>或具有设定height和overflow-y: scroll的自定义元素。 -
在可滚动容器上,添加
data-bs-spy="scroll"和data-bs-target="#navId",其中navId是关联导航的唯一id。如果元素内没有可聚焦元素,请务必同时包含tabindex="0"以确保键盘可访问性。 -
当滚动“被监听”的容器时,关联导航中的锚点链接会添加和移除
.active类。链接必须具有可解析的id目标,否则会被忽略。例如,<a href="#home">home</a>必须对应 DOM 中的某物,如<div id="home"></div> -
不可见的目标元素将被忽略。请参阅下方的不可见元素部分。
-
目标
id使用getElementById进行匹配,因此包含特殊字符或百分号编码字符的 id(例如#item.1、#section:overview或#%2Fpath)可以正确解析。
检测
滚动监听使用 IntersectionObserver 来跟踪区块,而无需轮询 scroll-position。检测是确定性的,完全由滚动容器顶部附近的激活线驱动。
- 激活的区块是其顶部已滚动过激活线的最深区块,就像你当前正在阅读的区块。
- 当滚动经过两个标题之间的间隙时,最后激活的区块会保持激活状态,直到下一个区块越过该线。
- 在容器的最顶部,在任何区块越过该线之前,第一个区块保持激活。
- 在容器的最底部,即使最后一个区块的顶部从未到达该线,它也会被激活(这对于较短的末尾区块很方便)。
使用 topMargin(从滚动根顶部算起更友好的 % 或 px 值,例如 96px 以位于吸顶导航栏下方)设置激活线的位置,或使用原始 IntersectionObserver 的 rootMargin 字符串完全掌控。请参阅选项。
跳转到调试叠加层部分,以可视化激活线的实际效果。
示例
导航栏
滚动导航栏下方的区域,观察激活类的变化。打开菜单,观察菜单项也会被高亮。
First heading
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Second heading
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Third heading
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Fourth heading
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Fifth heading
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
<nav id="navbar-example2" class="navbar bg-1 px-3 mb-3">
<a class="navbar-brand" href="#">Navbar</a>
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link" href="#scrollspyHeading1">First</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#scrollspyHeading2">Second</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#" role="button" data-bs-toggle="menu" aria-expanded="false">Menu</a>
<div class="menu">
<a class="menu-item" href="#scrollspyHeading3">Third</a>
<a class="menu-item" href="#scrollspyHeading4">Fourth</a>
<hr class="menu-divider">
<a class="menu-item" href="#scrollspyHeading5">Fifth</a>
</div>
</li>
</ul>
</nav>
<div data-bs-spy="scroll" data-bs-target="#navbar-example2" data-bs-root-margin="0px 0px -40%" data-bs-smooth-scroll="true" class="scrollspy-example bg-1 p-3 rounded-2" tabindex="0">
<h4 id="scrollspyHeading1">First heading</h4>
<p>...</p>
<h4 id="scrollspyHeading2">Second heading</h4>
<p>...</p>
<h4 id="scrollspyHeading3">Third heading</h4>
<p>...</p>
<h4 id="scrollspyHeading4">Fourth heading</h4>
<p>...</p>
<h4 id="scrollspyHeading5">Fifth heading</h4>
<p>...</p>
</div>嵌套导航
滚动监听也可用于嵌套的 .nav。如果嵌套的 .nav 为 .active,其父级也会变为 .active。滚动导航栏旁边的区域,观察激活类的变化。
Item 1
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Keep in mind that the JavaScript plugin tries to pick the right element among all that may be visible. Multiple visible scrollspy targets at the same time may cause some issues.
Item 1-1
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Keep in mind that the JavaScript plugin tries to pick the right element among all that may be visible. Multiple visible scrollspy targets at the same time may cause some issues.
Item 1-2
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Keep in mind that the JavaScript plugin tries to pick the right element among all that may be visible. Multiple visible scrollspy targets at the same time may cause some issues.
Item 2
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Keep in mind that the JavaScript plugin tries to pick the right element among all that may be visible. Multiple visible scrollspy targets at the same time may cause some issues.
Item 3
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Keep in mind that the JavaScript plugin tries to pick the right element among all that may be visible. Multiple visible scrollspy targets at the same time may cause some issues.
Item 3-1
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Keep in mind that the JavaScript plugin tries to pick the right element among all that may be visible. Multiple visible scrollspy targets at the same time may cause some issues.
Item 3-2
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Keep in mind that the JavaScript plugin tries to pick the right element among all that may be visible. Multiple visible scrollspy targets at the same time may cause some issues.
<div class="row">
<div class="col-4">
<nav id="navbar-example3" class="h-100 flex-column align-items-stretch pe-4 border-end">
<nav class="nav nav-pills flex-column">
<a class="nav-link" href="#item-1">Item 1</a>
<nav class="nav nav-pills flex-column">
<a class="nav-link ms-3 my-1" href="#item-1-1">Item 1-1</a>
<a class="nav-link ms-3 my-1" 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 ms-3 my-1" href="#item-3-1">Item 3-1</a>
<a class="nav-link ms-3 my-1" href="#item-3-2">Item 3-2</a>
</nav>
</nav>
</nav>
</div>
<div class="col-8">
<div data-bs-spy="scroll" data-bs-target="#navbar-example3" data-bs-smooth-scroll="true" class="scrollspy-example-2" tabindex="0">
<div id="item-1">
<h4>Item 1</h4>
<p>...</p>
</div>
<div id="item-1-1">
<h5>Item 1-1</h5>
<p>...</p>
</div>
<div id="item-1-2">
<h5>Item 1-2</h5>
<p>...</p>
</div>
<div id="item-2">
<h4>Item 2</h4>
<p>...</p>
</div>
<div id="item-3">
<h4>Item 3</h4>
<p>...</p>
</div>
<div id="item-3-1">
<h5>Item 3-1</h5>
<p>...</p>
</div>
<div id="item-3-2">
<h5>Item 3-2</h5>
<p>...</p>
</div>
</div>
</div>
</div>列表组
滚动监听也可用于 .list-group。滚动列表组旁边的区域,观察激活类的变化。
Item 1
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Item 2
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Item 3
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Item 4
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
<div class="row">
<div class="col-4">
<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>
<div class="col-8">
<div data-bs-spy="scroll" data-bs-target="#list-example" data-bs-smooth-scroll="true" class="scrollspy-example" tabindex="0">
<h4 id="list-item-1">Item 1</h4>
<p>...</p>
<h4 id="list-item-2">Item 2</h4>
<p>...</p>
<h4 id="list-item-3">Item 3</h4>
<p>...</p>
<h4 id="list-item-4">Item 4</h4>
<p>...</p>
</div>
</div>
</div>简单锚点
滚动监听不限于导航组件和列表组,因此它可用于当前文档中的任何 <a> 锚点元素。滚动区域,观察 .active 类的变化。
Item 1
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Item 2
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Item 3
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Item 4
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
Item 5
This is some placeholder content for the scrollspy page. Note that as you scroll down the page, the appropriate navigation link is highlighted. It’s repeated throughout the component example. We keep adding some more example copy here to emphasize the scrolling and highlighting.
<div class="row">
<div class="col-4">
<div id="simple-list-example" class="d-flex flex-column gap-2 simple-list-example-scrollspy text-center">
<a class="p-1 rounded" href="#simple-list-item-1">Item 1</a>
<a class="p-1 rounded" href="#simple-list-item-2">Item 2</a>
<a class="p-1 rounded" href="#simple-list-item-3">Item 3</a>
<a class="p-1 rounded" href="#simple-list-item-4">Item 4</a>
<a class="p-1 rounded" href="#simple-list-item-5">Item 5</a>
</div>
</div>
<div class="col-8">
<div data-bs-spy="scroll" data-bs-target="#simple-list-example" data-bs-smooth-scroll="true" class="scrollspy-example" tabindex="0">
<h4 id="simple-list-item-1">Item 1</h4>
<p>...</p>
<h4 id="simple-list-item-2">Item 2</h4>
<p>...</p>
<h4 id="simple-list-item-3">Item 3</h4>
<p>...</p>
<h4 id="simple-list-item-4">Item 4</h4>
<p>...</p>
<h4 id="simple-list-item-5">Item 5</h4>
<p>...</p>
</div>
</div>
</div>调试叠加层
很难想象滚动监听究竟在哪里判定某个区块处于激活状态。由于我们的文档页面在目录(右侧导航)上使用了滚动监听,你可以启用调试叠加层,在视口上绘制红色参考线以说明其行为。
- 靠近顶部的红色虚线是激活线。 当区块的标题滚动到该线上方时,该区块变为激活状态。在这些文档中,它位于
96px处,恰好在导航栏下方,并留有一点呼吸空间。 - 当你到达页面底部时,红色底部区域会亮起。 在这里,即使最后一个区块的标题从未到达激活线,它也会保持激活状态。
滚动页面,观察当标题越过该线时目录中高亮项的变化。参考线的位置使用与插件相同的 topMargin/rootMargin 检测数学计算得出。
不可见元素
不可见的目标元素将被忽略,其对应的导航项也不会获得 .active 类。在不可见包裹元素中初始化的滚动监听实例将忽略所有目标元素。一旦包裹元素变为可见,请使用 refresh 方法检查可观察元素。
document.querySelectorAll('#nav-tab>[data-bs-toggle="tab"]').forEach(el => {
el.addEventListener('shown.bs.tab', () => {
const target = el.getAttribute('data-bs-target')
const scrollElem = document.querySelector(`${target} [data-bs-spy="scroll"]`)
bootstrap.ScrollSpy.getOrCreateInstance(scrollElem).refresh()
})
})
用法
通过 data 属性
要轻松地为顶栏导航添加滚动监听行为,请为要监听的元素(通常为 <body>)添加 data-bs-spy="scroll"。然后添加 data-bs-target 属性,值为任何 Bootstrap .nav 组件的父元素的 id 或类名。
| 属性 | 描述 |
|---|---|
data-bs-spy="scroll" | 在可滚动元素(通常是 <body>)上启用滚动监听。 |
data-bs-target | 导航的 CSS 选择器,其链接与被监听元素中的区块相匹配。 |
<body data-bs-spy="scroll" data-bs-target="#navbar-example">
...
<div id="navbar-example">
<ul class="nav nav-tabs" role="tablist">
...
</ul>
</div>
...
</body>
通过 JavaScript
const scrollSpy = new bootstrap.ScrollSpy(document.body, {
target: '#navbar-example'
})
依赖
The scrollspy plugin requires the following JavaScript files if you’re building Bootstrap’s JS from source:
| File | Description |
|---|---|
js/src/scrollspy.ts | Main scrollspy component |
js/src/base-component.ts | Base component class |
js/src/dom/data.ts | Element data store |
js/src/dom/event-handler.ts | Event handling utilities |
js/src/dom/manipulator.ts | Data attribute manipulation |
js/src/dom/selector-engine.ts | DOM selector utilities |
js/src/util/config.ts | Configuration base class |
js/src/util/index.ts | Core utility functions |
选项
As options can be passed via data attributes or JavaScript, you can append an option name to data-bs-, as in data-bs-animation="{value}". Make sure to change the case type of the option name from “camelCase” to “kebab-case” when passing the options via data attributes. For example, use data-bs-custom-class="beautifier" instead of data-bs-customClass="beautifier".
All components support a reserved data attribute data-bs-config that can house simple component configuration as a JSON string. When an element has data-bs-config='{"delay":0, "title":123}' and data-bs-title="456" attributes, the final title value will be 456 and the separate data attributes will override values given on data-bs-config. In addition, existing data attributes are able to house JSON values like data-bs-delay='{"show":0,"hide":150}'.
The final configuration object is the merged result of data-bs-config, data-bs-, and js object where the latest given key-value overrides the others.
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
rootMargin | string, null | null | IntersectionObserver rootMargin 的高级覆盖。设置后它优先于 topMargin,并直接传递给观察器(例如 0px 0px -40%)。保留 null 以从 topMargin 派生激活线。 |
smoothScroll | boolean | false | 当用户点击指向滚动监听可观察元素的链接时启用平滑滚动。滚动稳定后,URL 哈希和焦点会移到目标区块。 |
target | string, DOM element | null | 指定要应用滚动监听插件的元素。 |
threshold | array | [0] | 计算滚动位置时,IntersectionObserver threshold 的有效输入。 |
topMargin | string | 12% | 激活线的位置,从滚动根顶部测量。接受百分比(12%)或像素(96px,例如位于吸顶导航栏下方)。设置 rootMargin 时会被忽略。 |
方法
| 方法 | 描述 |
|---|---|
dispose | 销毁元素的滚动监听。(移除 DOM 元素上存储的数据) |
getInstance | 静态 方法,用于获取与 DOM 元素关联的滚动监听实例。 |
getOrCreateInstance | 静态 方法,用于获取与 DOM 元素关联的滚动监听实例,如果尚未初始化则创建一个新实例。 |
refresh | 在 DOM 中添加或移除元素时,你需要调用 refresh 方法。 |
以下是使用 refresh 方法的示例:
const dataSpyList = document.querySelectorAll('[data-bs-spy="scroll"]')
dataSpyList.forEach(dataSpyEl => {
bootstrap.ScrollSpy.getInstance(dataSpyEl).refresh()
})
事件
| 事件 | 描述 |
|---|---|
activate.bs.scrollspy | 每当滚动监听激活某个锚点时,都会在滚动元素上触发此事件。 |
const firstScrollSpyEl = document.querySelector('[data-bs-spy="scroll"]')
firstScrollSpyEl.addEventListener('activate.bs.scrollspy', () => {
// do something...
})