linkedin behance copy

Scrollspy

Mettez automatiquement à jour la navigation Bootstrap ou répertoriez les composants de groupe en fonction de la position de défilement pour indiquer quel lien est actuellement actif dans la fenêtre d'affichage.

Comment ça fonctionne

Scrollspy a quelques exigences pour fonctionner correctement :

Une fois implémenté avec succès, votre groupe de navigation ou de liste sera mis à jour en conséquence, déplaçant la .active classe d'un élément à l'autre en fonction de leurs cibles associées.

Conteneurs déroulants et accès au clavier

Si vous créez un conteneur à défilement (autre que le <body>), assurez-vous d'avoir un height ensemble et overflow-y: scroll; de lui appliquer, à côté d'un tabindex="0" pour garantir l'accès au clavier.

Exemple dans la barre de navigation

Faites défiler la zone sous la barre de navigation et regardez la classe active changer. Les éléments de la liste déroulante seront également mis en surbrillance.

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 navbar-light bg-light px-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-offset="0" class="scrollspy-example" 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>

Exemple avec navigation imbriquée

Scrollspy fonctionne également avec les .navs. imbriqués. Si un imbriqué .nav est .active, ses parents le seront également .active. Faites défiler la zone à côté de la barre de navigation et regardez la classe active changer.

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 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.

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.

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 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.

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.

<nav id="navbar-example3" class="navbar navbar-light bg-light flex-column align-items-stretch p-3">
  <a class="navbar-brand" href="#">Navbar</a>
  <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 data-bs-spy="scroll" data-bs-target="#navbar-example3" data-bs-offset="0" tabindex="0">
  <h4 id="item-1">Item 1</h4>
  <p>...</p>
  <h5 id="item-1-1">Item 1-1</h5>
  <p>...</p>
  <h5 id="item-1-2">Item 1-2</h5>
  <p>...</p>
  <h4 id="item-2">Item 2</h4>
  <p>...</p>
  <h4 id="item-3">Item 3</h4>
  <p>...</p>
  <h5 id="item-3-1">Item 3-1</h5>
  <p>...</p>
  <h5 id="item-3-2">Item 3-2</h5>
  <p>...</p>
</div>

Exemple avec list-group

Scrollspy fonctionne également avec .list-groups. Faites défiler la zone à côté du groupe de la liste et regardez la classe active changer.

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 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 data-bs-spy="scroll" data-bs-target="#list-example" data-bs-offset="0" 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>

Utilisation

Via les attributs de données

Pour ajouter facilement un comportement scrollspy à votre navigation dans la barre supérieure, ajoutez data-bs-spy="scroll" à l'élément que vous souhaitez espionner (le plus souvent, ce serait le <body>). Ajoutez ensuite l' data-bs-target attribut avec l'ID ou la classe de l'élément parent de n'importe quel .nav composant Bootstrap.

body {
  position: relative;
}
<body data-bs-spy="scroll" data-bs-target="#navbar-example">
  ...
  <div id="navbar-example">
    <ul class="nav nav-tabs" role="tablist">
      ...
    </ul>
  </div>
  ...
</body>

Via JavaScript

Après avoir ajouté position: relative; dans votre CSS, appelez le scrollspy via JavaScript :

var scrollSpy = new bootstrap.ScrollSpy(document.body, {
  target: '#navbar-example'
})

Cibles d'ID résolubles requises

Les liens de la barre de navigation doivent avoir des cibles d'ID résolubles. Par exemple, un <a href="#home">home</a> doit correspondre à quelque chose dans le DOM comme <div id="home"></div>.

Éléments cibles non visibles ignorés

Les éléments cibles qui ne sont pas visibles seront ignorés et leurs éléments de navigation correspondants ne seront jamais mis en surbrillance.

Méthodes

Rafraichir

Lorsque vous utilisez scrollspy en conjonction avec l'ajout ou la suppression d'éléments du DOM, vous devrez appeler la méthode refresh comme ceci :

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

Disposer

Détruit le scrollspy d'un élément. (Supprime les données stockées sur l'élément DOM)

getInstance

Méthode statique qui permet d'obtenir l'instance scrollspy associée à un élément DOM

var scrollSpyContentEl = document.getElementById('content')
var scrollSpy = bootstrap.ScrollSpy.getInstance(scrollSpyContentEl) // Returns a Bootstrap scrollspy instance

getOrCreateInstance

Méthode statique qui permet d'obtenir l'instance de scrollspy associée à un élément DOM, ou d'en créer une nouvelle au cas où elle n'aurait pas été initialisée

var scrollSpyContentEl = document.getElementById('content')
var scrollSpy = bootstrap.ScrollSpy.getOrCreateInstance(scrollSpyContentEl) // Returns a Bootstrap scrollspy instance

Options

Les options peuvent être transmises via des attributs de données ou JavaScript. Pour les attributs de données, ajoutez le nom de l'option à data-bs-, comme dans data-bs-offset="".

Nom Type Défaut Description
offset number 10 Pixels à décaler du haut lors du calcul de la position du défilement.
method string auto Trouve dans quelle section se trouve l'élément espionné. auto choisira la meilleure méthode pour obtenir les coordonnées de défilement. offset utilisera la Element.getBoundingClientRect() méthode pour obtenir les coordonnées de défilement. position utilisera les propriétés HTMLElement.offsetTop et HTMLElement.offsetLeft pour obtenir les coordonnées de défilement.
target string | jQuery object | DOM element Spécifie l'élément pour appliquer le plugin Scrollspy.

Evènements

Type d'évènement Description
activate.bs.scrollspy Cet événement se déclenche sur l'élément de défilement chaque fois qu'un nouvel élément est activé par le scrollspy.
var firstScrollSpyEl = document.querySelector('[data-bs-spy="scroll"]')
firstScrollSpyEl.addEventListener('activate.bs.scrollspy', function () {
  // do something...
})

© 2010-2022 Quazerty.