Перейти к основному контенту Перейти к навигации документации

Отслеживание прокрутки (Scrollspy)

Автоматически обновляйте компоненты навигации Bootstrap или группы списков на основе позиции прокрутки, чтобы указать, какая ссылка в данный момент активна в области просмотра.

Как это работает

Scrollspy переключает класс .active на элементах якорей (<a>) когда элемент с id, на который ссылается href якоря, прокручивается в поле зрения. Scrollspy лучше всего использовать в сочетании с Bootstrap компонентом nav или группой списков, но он также будет работать с любыми элементами якорей на текущей странице. Вот как это работает.

  • Для начала scrollspy требует две вещи: навигацию, группу списков или простой набор ссылок, плюс прокручиваемый контейнер. Прокручиваемым контейнером может быть <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>

  • Целевые элементы, которые не видны, будут проигнорированы. См. раздел Невидимые элементы ниже.

Примеры

Навигационная панель

Прокрутите область ниже навигационной панели и наблюдайте, как изменяется активный класс. Откройте выпадающее меню и наблюдайте, как элементы выпадающего списка также подсвечиваются.

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-body-tertiary 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 dropdown">
      <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false">Dropdown</a>
      <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="#scrollspyHeading3">Third</a></li>
        <li><a class="dropdown-item" href="#scrollspyHeading4">Fourth</a></li>
        <li><hr class="dropdown-divider"></li>
        <li><a class="dropdown-item" href="#scrollspyHeading5">Fifth</a></li>
      </ul>
    </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-body-tertiary 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>

Вложенная навигация

Scrollspy также работает с вложенными .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>

Группа списков

Scrollspy также работает с .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>

Простые якоря

Scrollspy не ограничивается компонентами nav и группами списков, поэтому он будет работать с любыми элементами якорей <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-offset="0" 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>

Невидимые элементы

Целевые элементы, которые не видны, будут проигнорированы, и соответствующие им элементы навигации не получат класс .active. Экземпляры Scrollspy, инициализированные в невидимой обертке, будут игнорировать все целевые элементы. Используйте метод 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

Чтобы легко добавить поведение scrollspy к вашей верхней навигации, добавьте data-bs-spy="scroll" к элементу, за которым вы хотите следить (чаще всего это будет <body>). Затем добавьте атрибут data-bs-target с id или именем класса родительского элемента любого компонента Bootstrap .nav.

<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'
})

Опции

Поскольку опции могут передаваться через атрибуты данных или JavaScript, вы можете добавить имя опции к data-bs-, например, data-bs-animation="{value}". Обязательно изменяйте стиль написания имени опции с “camelCase” на “kebab-case” при передаче опций через атрибуты данных. Например, используйте data-bs-custom-class="beautifier" вместо data-bs-customClass="beautifier".

Начиная с Bootstrap 5.2.0, все компоненты поддерживают экспериментальный зарезервированный атрибут данных data-bs-config, который может содержать простую конфигурацию компонента в виде строки JSON. Когда элемент имеет атрибуты data-bs-config='{"delay":0, "title":123}' и data-bs-title="456", окончательное значение title будет 456, а отдельные атрибуты данных переопределяют значения, указанные в data-bs-config. Кроме того, существующие атрибуты данных могут содержать значения JSON, такие как data-bs-delay='{"show":0,"hide":150}'.

Окончательный объект конфигурации — это объединенный результат data-bs-config, data-bs- и js object, где последний заданный ключ-значение переопределяет другие.

НазваниеТипПо умолчаниюОписание
rootMarginstring0px 0px -25%Intersection Observer rootMargin допустимые единицы при вычислении позиции прокрутки.
smoothScrollbooleanfalseВключает плавную прокрутку, когда пользователь нажимает на ссылку, которая ссылается на наблюдаемые элементы ScrollSpy.
targetstring, DOM elementnullУказывает элемент для применения плагина Scrollspy.
thresholdarray[0.1, 0.5, 1]IntersectionObserver threshold допустимый ввод при вычислении позиции прокрутки.

Устаревшие опции

До v5.1.3 мы использовали опции offset и method, которые теперь устарели и заменены на rootMargin. Для поддержания обратной совместимости мы продолжим парсить данный offset в rootMargin, но эта функция будет удалена в v6.

Методы

МетодОписание
disposeУничтожает scrollspy элемента. (Удаляет сохраненные данные на DOM элементе)
getInstanceСтатический метод для получения экземпляра scrollspy, связанного с DOM элементом.
getOrCreateInstanceСтатический метод для получения экземпляра scrollspy, связанного с DOM элементом, или создания нового в случае, если он не был инициализирован.
refreshПри добавлении или удалении элементов в DOM вам нужно будет вызвать метод refresh.

Вот пример использования метода refresh:

const dataSpyList = document.querySelectorAll('[data-bs-spy="scroll"]')
dataSpyList.forEach(dataSpyEl => {
  bootstrap.ScrollSpy.getInstance(dataSpyEl).refresh()
})

События

СобытиеОписание
activate.bs.scrollspyЭто событие запускается на элементе прокрутки всякий раз, когда якорь активируется scrollspy.
const firstScrollSpyEl = document.querySelector('[data-bs-spy="scroll"]')
firstScrollSpyEl.addEventListener('activate.bs.scrollspy', () => {
  // do something...
})