Bootstrap JS Scrollspy


JS Scrollspy

Scrollspy digunakan untuk memperbarui tautan secara otomatis dalam daftar navigasi berdasarkan posisi gulir.

Untuk tutorial tentang Scrollspy, baca Tutorial Bootstrap Scrollspy kami .


Melalui data-* Atribut

Tambahkan data-spy="scroll"ke elemen yang harus digunakan sebagai area yang dapat digulir (seringkali ini adalah <body>elemennya).

Kemudian tambahkan data-targetatribut dengan nilai id atau nama kelas bilah navigasi ( .navbar). Ini untuk memastikan bahwa navbar terhubung dengan area yang dapat digulir.

Perhatikan bahwa elemen yang dapat digulir harus cocok dengan ID tautan di dalam item daftar bilah navigasi ( <div id="section1">cocok <a href="#section1">).

Atribut opsional data-offsetmenentukan jumlah piksel untuk diimbangi dari atas saat menghitung posisi gulir. Ini berguna ketika Anda merasa bahwa tautan di dalam bilah navigasi mengubah status aktif terlalu cepat atau terlalu dini saat melompat ke elemen yang dapat digulir. Standarnya adalah 10 piksel.

Memerlukan pemosisian relatif: Elemen dengan data-spy="scroll" memerlukan properti posisi CSS , dengan nilai "relatif" agar berfungsi dengan baik.

Contoh

<!-- The scrollable area -->
<body data-spy="scroll" data-target=".navbar" data-offset="50">

<!-- The navbar - The <a> elements are used to jump to a section in the scrollable area -->
<nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="#section1">Section 1</a>
    </li>
  ....
  </ul>
</nav>

<!-- Section 1 -->
<div id="section1">
  <h1>Section 1</h1>
  <p>Try to scroll this page and look at the navigation bar while scrolling!</p>
</div>
...

</body>

Melalui JavaScript

Aktifkan secara manual dengan:

Contoh

$('body').scrollspy({target: ".navbar"})

Opsi Scrollspy

Opsi dapat diteruskan melalui atribut data atau JavaScript. Untuk atribut data, tambahkan nama opsi ke data-, seperti pada data-offset="".

Name Type Default Description Try it
offset number 10 Specifies the number of pixels to offset from top when calculating the position of scroll

Metode Scrollspy

Tabel berikut mencantumkan semua metode scrollspy yang tersedia.

Method Description
.scrollspy("refresh") When adding and removing elements from the scrollspy, this method can be used to refresh the document
.scrollspy("dispose") Destroys the scrollspy

Acara Scrollspy

Tabel berikut mencantumkan semua peristiwa scrollspy yang tersedia.

Event Description
activate.bs.scrollspy Occurs when a new item becomes activated by the scrollspy