By GokiSoft.Com| 19:26 12/10/2020|
Tài Liệu Bootstrap

Bootstrap 4 Scrollspy (Advanced)

Bootstrap 4 Scrollspy

Scrollspy được sử dụng để tự động cập nhật các liên kết trong danh sách điều hướng (navigation list) dựa trên vị trí scroll.



Cách để tạo một Scrollspy

Ví dụ sau đây cho thấy cách tạo một scrollspy:

Ví dụ

<!-- 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><a href="#section1">Section 1</a></li>
    ...
</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>

Giải thích ví dụ

Add data-spy="scroll" cho phần tử gọi là "scrollable area" - vùng có thể cuộn (thường là phần tử <body>).

Sau đó add thuộc tính data-target=".navbar để đảm bảo rằng navbar được kết nối với scrollable area.

Lưu ý rằng phần tử scrollable có ID phải trùng với các link bên trong list items của navbar (<div id="section1"> với <a href="#section1">).

Thuộc tính data-offset chỉ định số lượng pixel cần bù từ trên xuống khi tính toán vị trí scroll. Nó rất hữu ích khi bạn cảm thấy links bên trong navbar thay đổi trạng thái active quá sớm hoặc quá muộn khi nhảy tới thành phần scrollable tiếp theo. Mặc định là 10 pixels.

Yêu cầu relative positioning: Phần tử với data-spy="scroll" yêu cầu thuộc tính position CSS, với giá trị là "relative".


Scrollspy Vertical Menu

Trong ví dụ này, chúng ta sử dụng Bootstrap's vertical navigation pills (Navbar dọc) với vai trò là menu bên trái:

Ví dụ

<body data-spy="scroll" data-target="#myScrollspy" data-offset="1">

  <div class="container-fluid">
    <div class="row">
      <nav class="col-sm-3 col-4" id="myScrollspy">
        <ul class="nav nav-pills flex-column">
          <li class="nav-item">
            <a class="nav-link active" href="#section1">Section 1</a>
          </li>
          ...
        </ul>
      </nav>
      <div class="col-sm-9 col-8">
        <div id="section1">
          <h1>Section 1</h1>
          <p>Try to scroll this page and look at the menu while scrolling!</p>
        </div>
        ...
      </div>
    </div>
  </div>

</body>