Bootstrap JS Scrollspy
JS Scrollspy
Scrollspyは、スクロール位置に基づいてナビゲーションリスト内のリンクを自動的に更新するために使用されます。
Scrollspyに関するチュートリアルについては、BootstrapScrollspyチュートリアルをお読みください。
データ経由-*属性
data-spy="scroll"
スクロール可能領域として使用する必要がある要素に追加します(多くの場合、これは<body>
要素です)。
data-target
次に、ナビゲーションバーのidまたはクラス名の値を使用して属性を追加します( .navbar
)。これは、ナビゲーションバーがスクロール可能な領域に接続されていることを確認するためです。
スクロール可能な要素は、ナビゲーションバーのリストアイテム内のリンクのIDと一致する必要があることに注意してください(<div id="section1">
一致<a href="#section1">
)。
オプションのdata-offset
属性は、スクロールの位置を計算するときに上からオフセットするピクセル数を指定します。これは、スクロール可能な要素にジャンプするときに、ナビゲーションバー内のリンクがアクティブ状態を変更するのが早すぎたり早すぎたりする場合に役立ちます。デフォルトは10ピクセルです。
相対配置が必要: data-spy = "scroll"の要素には、正しく機能するために「relative」の値を持つCSSpositionプロパティが必要です。
例
<!-- 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>
JavaScript経由
次のコマンドで手動で有効にします。
例
$('body').scrollspy({target: ".navbar"})
Scrollspyオプション
オプションは、データ属性またはJavaScriptを介して渡すことができます。データ属性の場合、data-offset = ""のように、オプション名をdata-に追加します。
Name | Type | Default | Description | Try it |
---|---|---|---|---|
offset | number | 10 | Specifies the number of pixels to offset from top when calculating the position of scroll |
Scrollspyメソッド
次の表に、使用可能なすべてのscrollspyメソッドを示します。
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 |
Scrollspyイベント
次の表に、使用可能なすべてのスクロールスパイイベントを示します。
Event | Description |
---|---|
activate.bs.scrollspy | Occurs when a new item becomes activated by the scrollspy |