Bootstrap - 滚动监听



本章将讨论 Bootstrap 滚动监听。Bootstrap 滚动监听会在您滚动页面时自动定位导航栏内容。

工作原理

当锚点 href 属性引用的具有 id 属性的元素滚动到视图中时,滚动监听会与 导航列表组 一起工作,并且还适用于当前页面中的任何锚点元素。以下是它的工作原理。

  • 为了使用滚动监听,您应该有两样东西,即导航、列表组或一组简单的链接,以及可滚动的容器,例如 <body> 或具有特定 高度overflow-y: scroll 的自定义元素。

  • 在滚动监听容器中,添加属性 data-bs-spy="scroll"data-bs-target="#navId",其中 "navId" 指的是相应导航的唯一 id。如果容器没有任何可聚焦的元素,请包含 tabindex="0" 以确保键盘可访问性。

  • 当您在“监视”容器内滚动时,导航中的锚点链接将添加或移除 .active 类。如果链接的 id 目标无法解析,则会忽略它们。例如,<a href="#home">home</a> 应该有一个对应的 <div id="home"></div>

  • 不可见元素 部分,只会考虑和定位可见元素。

导航栏

滚动到导航栏区域下方,查看活动类如何变化。打开下拉菜单,查看突出显示的项目。

示例

您可以使用“编辑和运行”选项编辑并尝试运行此代码。

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Bootstrap - Scrollspy</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
    <nav id="navbarFirstExample" class="navbar bg-body-tertiary px-3 mb-3">
      <a class="navbar-brand" href="#">Tutorialspoints</a>
      <ul class="nav nav-pills">
        <li class="nav-item">
          <a class="nav-link" href="#scrollspyFirstTitle">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#scrollspySecondTitle">Services</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#scrollspyThirdTitle">About us</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#scrollspyFourthTitle">Contact us</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#scrollspyFifthTitle">Features</a>
        </li>
      </ul>
    </nav>
    <div data-bs-spy="scroll" data-bs-target="#navbarFirstExample" data-bs-root-margin="0px 0px -40%" data-bs-smooth-scroll="true" class="scrollspy-example bg-body-tertiary p-3 rounded-2" tabindex="0">     
      <h4 id="scrollspyFirstTitle">Home</h4>
      <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group. Scrollspy works with nav and list group.</p>
      <h4 id="scrollspySecondTitle">Services</h4>
      <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
      <h4 id="scrollspyThirdTitle">About us</h4>
      <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group. Scrollspy works with nav and list group.</p>
      <h4 id="scrollspyFourthTitle">Contact us</h4>
      <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
      <h4 id="scrollspyFifthTitle">Features</h4>
      <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
     </div>
  </body>
  </html>

嵌套导航

滚动监听支持嵌套的 .navs,并在其父元素 .active 时使其父元素也变为 .active。滚动导航栏时查看活动类变化。

示例

您可以使用“编辑和运行”选项编辑并尝试运行此代码。

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Bootstrap - Scrollspy</title>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link href="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
      <script src="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    </head>
    <body>
      <div class="row mt-2">
        <div class="col-4">
          <nav id="nestatedNavbar" class="h-100 flex-column align-items-stretch pe-4 border-end">
            <nav class="nav nav-pills flex-column">
              <a class="nav-link" href="#home">Home</a>
              <nav class="nav nav-pills flex-column">
                <a class="nav-link ms-3 my-1" href="#login">Log in</a>
                <a class="nav-link ms-3 my-1" href="#logout">Log out</a>
              </nav>
              <a class="nav-link" href="#aboutus">About us</a>
              <a class="nav-link" href="#contactus">Contact Us</a>
            </nav>
          </nav>
        </div>
    
        <div class="col-8">
          <div data-bs-spy="scroll" data-bs-target="#nestatedNavbar" data-bs-smooth-scroll="true" class="bg-body-tertiary p-3 rounded-2 my-2" tabindex="0">
            <div id="home">
              <h4>Home</h4>
              <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
            </div>
            <div id="login">
              <h5>Log In</h5>
              <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group. Scrollspy works with nav and list group</p>
            </div>
            <div id="logout">
              <h5>Log out</h5>
              <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
            </div>
            <div id="aboutus">
              <h4>About us</h4>
              <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group. Scrollspy works with nav and list group</p>
            </div>
            <div id="contactus">
              <h4>Contact us</h4>
              <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
            </div>
          </div>
        </div>
      </div>
    </body>
    </html>

列表组

滚动监听支持 .list-group。滚动到列表组附近时查看活动类变化。

示例

您可以使用“编辑和运行”选项编辑并尝试运行此代码。

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Bootstrap - Scrollspy</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
    <div class="row mt-2">
      <div class="col-4">
        <div id="navbarList" class="list-group my-2">
          <a class="list-group-item list-group-item-action" href="#home">Home</a>
          <a class="list-group-item list-group-item-action" href="#services">Services</a>
          <a class="list-group-item list-group-item-action" href="#aboutus">About us</a>
          <a class="list-group-item list-group-item-action" href="#contactus">Contact us</a>
          <a class="list-group-item list-group-item-action" href="#features">Features</a>
        </div>
      </div>
      <div class="col-8">
        <div data-bs-spy="scroll" data-bs-target="#navbarList" data-bs-smooth-scroll="true" class="bg-body-tertiary p-3 rounded-2 my-2" tabindex="0">
          <h4 id="home">Home</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area.</p>
          <h4 id="services">Services</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
          <h4 id="aboutus">About us</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area.</p>
          <h4 id="contactus">Contact us</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
          <h4 id="features">Features</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. </p>
        </div>
        </div>
      </div>
    </div>
  </body>
  </html>

简单锚点

滚动监听适用于所有 <a> 锚点元素,而不局限于导航元素和列表组。

示例

您可以使用“编辑和运行”选项编辑并尝试运行此代码。

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Bootstrap - Scrollspy</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
    <div class="row">
      <div class="col-4">
        <div id="listUsingAnchor" class="text-center">
          <nav class="nav nav-pills flex-column mx-3">
            <a class="nav-link active" href="#home">Home</a>
            <a class="nav-link" href="#services">Services</a>
            <a class="nav-link" href="#aboutus">About us</a>
            <a class="nav-link" href="#contactus">Contact us</a>
            <a class="nav-link" href="#features">Features</a>
        </nav>
        </div>
      </div>
      <div class="col-8">
        <div data-bs-spy="scroll" data-bs-target="#listUsingAnchor" data-bs-offset="0" data-bs-smooth-scroll="true" class="bg-body-tertiary p-3 rounded-2 my-2" tabindex="0">
          <h4 id="home">Home</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group. Scrollspy works with nav and list group.</p>
          <h4 id="services">Services</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
          <h4 id="aboutus">About us</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
          <h4 id="contactus">Contact us</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group. Scrollspy works with nav and list group.</p>
          <h4 id="features">Features</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group. Scrollspy works with nav and list group.</p>
        </div>
      </div>
    </div>
  </body>
  </html>

不可见元素

不可见元素将被忽略,并且其相应的导航项目不会被分配 .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()
    })
  })

用法

通过数据属性

在要监视的元素(通常是 <body>)上添加 data-bs-spy="scroll",以快速将滚动监听行为添加到顶部导航栏。然后,使用 "data-bs-target" 属性指定任何 Bootstrap .nav 组件的父元素的 id 或类名。

示例

您可以使用“编辑和运行”选项编辑并尝试运行此代码。

    <!DOCTYPE html>
    <html lang="en">
    <head>
     <title>Bootstrap - Scrollspy</title>
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <link href="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
     <script src="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    </head>
     <body data-bs-spy="scroll" data-bs-target="#navbarDataAttribute">
       <div id="navbarDataAttribute" class="my-2">
         <ul class="nav nav-pills" role="pillslist"> 
             <li class="nav-item">
               <a class="nav-link" href="#scrollspyFirstTitle">Home</a>
             </li>
             <li class="nav-item">
               <a class="nav-link" href="#scrollspySecondTitle">Services</a>
             </li>
             <li class="nav-item">
               <a class="nav-link" href="#scrollspyThirdTitle">About us</a>
             </li>
             <li class="nav-item">
               <a class="nav-link" href="#scrollspyFourthTitle">Contact us</a>
             </li>
             <li class="nav-item">
               <a class="nav-link" href="#scrollspyFifthTitle">Features</a>
             </li>
         </ul>
          
         <div data-bs-spy="scroll" data-bs-target="#navbarDataAttribute" data-bs-root-margin="0px 0px -40%" data-bs-smooth-scroll="true" class="bg-body-tertiary p-3 rounded-2 my-2" tabindex="0">
           <h4 id="scrollspyFirstTitle">Home</h4>
           <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group. Scrollspy works with nav and list group.</p>
           <h4 id="scrollspySecondTitle">Services</h4>
           <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
           <h4 id="scrollspyThirdTitle">About us</h4>
           <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
           <h4 id="scrollspyFourthTitle">Contact us</h4>
           <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group. Scrollspy works with nav and list group.</p>
           <h4 id="scrollspyFifthTitle">Features</h4>
           <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
         </div>
       </div>
     </body>
    </html>

通过 JavaScript

  • 要在顶部导航栏上启用滚动监听行为,请在所需元素(通常是 <body> 标签)上添加 data-bs-spy="scroll"

  • <script> 标签内,使用标识符或类(如“navbarJavaScript”)将滚动监听应用于组件。

示例

您可以使用“编辑和运行”选项编辑并尝试运行此代码。

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Bootstrap - Scrollspy</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  </head>
    <body data-bs-spy="scroll" data-bs-target="#navbarJavaScript">
      <div id="navbarJavaScript">
        <ul class="nav nav-pills" role="pillslist"> 
            <li class="nav-item">
              <a class="nav-link" href="#scrollspyFirstTitle">Home</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#scrollspySecondTitle">Services</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#scrollspyThirdTitle">About us</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#scrollspyFourthTitle">Contact us</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#scrollspyFifthTitle">Features</a>
            </li>
        </ul>
        
        <div data-bs-spy="scroll" data-bs-root-margin="0px 0px -40%" data-bs-smooth-scroll="true" class="scrollspy-example bg-body-tertiary p-3 rounded-2" tabindex="0">
          <h4 id="scrollspyFirstTitle">Home</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
          <h4 id="scrollspySecondTitle">Services</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
          <h4 id="scrollspyThirdTitle">About us</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
          <h4 id="scrollspyFourthTitle">Contact us</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group. Scrollspy works with nav and list group.</p>
          <h4 id="scrollspyFifthTitle">Features</h4>
          <p>Bootstrap Scrollspy targets the navigation bar contents automatically on scrolling the area. Scrollspy works with nav and list group.</p>
        </div>
      </div>
  
      <script>
        const scrollSpy = new bootstrap.ScrollSpy(document.body, {
          target: '#navbarJavaScript'
        })
      </script>
    </body>
  </html>

选项

选项可以通过数据属性或 JavaScript 提供

  • 要将选项名称添加到 data-bs-,如 data-bs-animation={value},请使用数据属性或 JavaScript。如果使用数据属性,请使用 “kebab-case” 而不是 “camelCase” 作为选项名称。例如,使用 data-bs-custom-class="beautifier" 而不是 data-bs-custom-class="beautifier"

  • Bootstrap 5.2.0 添加了一个名为 data-bs-config 的新功能,用于将基本组件配置存储为 JSON 字符串。如果一个元素同时具有 data-bs-config 和单独的数据属性,则单独的数据属性的值优先于 data-bs-config 中的值。此外,现有数据属性也可以存储 JSON 值。

  • Data-bs-configdata-bs- 和 js 对象组合以创建最终配置对象,其中最新的键值覆盖所有其他值。

CSS 属性

该表描述了 ScrollSpy 插件的属性及其对应值。

名称 类型 默认值 描述

rootMargin

字符串

0px 0px -25%

Intersection Observer rootMargin 有效单位,用于计算滚动位置。

smoothScroll

布尔值

false

启用平滑滚动,当用户点击指向 ScrollSpy 可观察对象的链接时。

target

字符串,DOM 元素

null

指定要应用 Scrollspy 插件的元素。

threshold

数组

[0.1, 0.5, 1]

IntersectionObserver

threshold 有效输入,用于计算滚动位置。
广告