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/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/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/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/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/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/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/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/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/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
     <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/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/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/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 有效輸入,用於計算滾動位置。
廣告