Bootstrap 滾動監聽(Scrollspy)
滾動監聽(Scrollspy)插件,即自動更新導航插件,會根據滾動條的位置自動更新對應的導航目標。其基本的實現是隨著您的滾動。
如何創建滾動監聽
以下實例演示了如何創建滾動監聽:
實例
<!-- 可滾動區域 -->
<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>
<!-- 第一部分內容 -->
<div id="section1">
<h1>Section 1</h1>
<p>Try to scroll this page and look at the navigation bar while scrolling!</p>
</div>
...
</body>
實例解析
向您想要監聽的元素(通常是 body)添加 data-spy="scroll" 。
然後添加 data-target 屬性,它的值為導航欄的 id 或 class (.navbar)。這樣就可以聯繫上可滾動區域。
注意可滾動項元素上的 id (<div id="section1">) 必須匹配導航欄上的鏈接選項 (<a href="#section1">)。
可選項data-offset 屬性用於計算滾動位置時,距離頂部的偏移像素。 默認為 10 px。
設置相對定位: 使用 data-spy="scroll" 的元素需要將其 CSS position 屬性設置為 "relative" 才能起作用。
以下實例設置了垂直滾動監聽:
實例
<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 navigation list while scrolling!</p>
</div>
...
</div>
</div>
</div>
</body>