Bootstrap JS Scrollspy
JS Scrollspy
Scrollspy ใช้เพื่ออัปเดตลิงก์ในรายการการนำทางโดยอัตโนมัติตามตำแหน่งการเลื่อน
สำหรับบทแนะนำเกี่ยวกับ Scrollspy โปรดอ่านBootstrap Scrollspy Tutorialของเรา
ผ่าน data-* คุณสมบัติ
เพิ่มdata-spy="scroll"
ไปยังองค์ประกอบที่ควรใช้เป็นพื้นที่ที่เลื่อนได้ (มักจะเป็น<body>
องค์ประกอบ)
จากนั้นเพิ่มdata-target
แอตทริบิวต์ที่มีค่าของ id หรือชื่อคลาสของแถบนำทาง ( .navbar
) เพื่อให้แน่ใจว่าแถบนำทางเชื่อมต่อกับพื้นที่ที่เลื่อนได้
โปรดทราบว่าองค์ประกอบที่เลื่อนได้ต้องตรงกับ ID ของลิงก์ภายในรายการของแถบนำทาง ( <div id="section1">
match <a href="#section1">
)
แอตทริบิวต์ที่ เป็นตัวเลือกdata-offset
ระบุจำนวนพิกเซลที่จะออฟเซ็ตจากด้านบนเมื่อคำนวณตำแหน่งของการเลื่อน สิ่งนี้มีประโยชน์เมื่อคุณรู้สึกว่าลิงก์ภายในแถบนำทางเปลี่ยนสถานะใช้งานเร็วเกินไปหรือเร็วเกินไปเมื่อข้ามไปยังองค์ประกอบที่เลื่อนได้ ค่าเริ่มต้นคือ 10 พิกเซล
ต้องการตำแหน่งสัมพันธ์:องค์ประกอบที่มี data-spy="scroll" ต้องการ คุณสมบัติ ตำแหน่ง CSS โดยมีค่า "สัมพันธ์" เพื่อให้ทำงานได้อย่างถูกต้อง
ตัวอย่าง
<!-- 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- เช่นเดียวกับใน 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 |
วิธีการของ 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
ตารางต่อไปนี้แสดงรายการเหตุการณ์ scrollspy ที่มีอยู่ทั้งหมด
Event | Description |
---|---|
activate.bs.scrollspy | Occurs when a new item becomes activated by the scrollspy |