Bootstrap JS Scrollspy 插件

JS Scrollspy (scrollspy.js)

Scrollspy 插件用于根据滚动位置自动更新导航列表中的链接。

学习更多的 Scrollspy 的知识, 请访问本站的 Bootstrap 滚动监听教程

提示:Scrollspy 插件通常与其他插件一起使用。

通过 data-* 属性

data-spy="scroll" 添加到应该用作可滚动区域的元素(通常是 <body> 元素)。

然后使用导航栏(.navbar)的 id 值或类名添加 data-target 属性。这使得导航栏与可滚动区域关联起来。

请注意,可滚动元素必须与导航栏列表项内链接的 ID 匹配(<div id="section1"> 匹配 <a href="#section1">)。

可选的 data-offset 属性指定计算滚动位置时从顶部偏移的像素数。默认值为 10 像素。

需要相对定位:带有 data-spy="scroll" 的元素需要 CSS position 属性,其值为 "relative" 才能正常工作。

实例
  1. <!-- The scrollable area -->
  2. <body data-spy="scroll"
  3. data-target=".navbar" data-offset="50">
  4. <!-- The navbar - The <a> elements are used to jump to a section in the scrollable area -->
  5. <nav class="navbar navbar-inverse navbar-fixed-top">
  6. ...
  7. <ul class="nav navbar-nav">
  8. <li><a href="#section1">Section 1</a></li>
  9. ...
  10. </nav>
  11. <!-- Section 1 -->
  12. <div id="section1">
  13. <h1>Section 1</h1>
  14. <p>Try to scroll this page and look at the navigation bar while scrolling!</p>
  15. </div>
  16. ...
  17. </body>

通过 JavaScript

手动:

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

Scrollspy Options

Options 可以通过数据属性或 JavaScript 传递。对于数据属性,请将选项名称附加到 data-,如 data-offset=""

名称类型默认描述试一试
offsetnumber10指定计算滚动位置时从顶部偏移的像素数试一试

Scrollspy 方法

下表列出了所有可用的 scrollspy 方法。

方法描述试一试
.scrollspy("refresh")在 scrollspy 中添加和删除元素时,可以使用此方法刷新文档试一试

Scrollspy 事件

下表列出了所有可用的 scrollspy 事件。

事件描述试一试
activate.bs.scrollspy当 scrollspy 激活新项时发生试一试

更多实例

带滚动动画的 Scrollspy

如何将平滑页面滚动添加到同一页面上的锚点:

Smooth scrolling
  1. // Add scrollspy to <body>
  2. $('body').scrollspy({target: ".navbar", offset: 50});
  3. // Add smooth scrolling on all links inside the navbar
  4. $("#myNavbar a").on('click', function(event) {
  5. // Make sure this.hash has a value before overriding default behavior
  6. if (this.hash !== "") {
  7. // Prevent default anchor click behavior
  8. event.preventDefault();
  9. // Store hash
  10. var hash = this.hash;
  11. // Using jQuery's animate() method to add smooth page scroll
  12. // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
  13. $('html, body').animate({
  14. scrollTop: $(hash).offset().top
  15. }, 800, function(){
  16. // Add hash (#) to URL when done scrolling (default click behavior)
  17. window.location.hash = hash;
  18. });
  19. } // End if
  20. });
Scrollspy & Affix

Affix 插件与 Scrollspy 插件一起使用:

水平菜单 (导航条)
  1. <body data-spy="scroll" data-target=".navbar" data-offset="50">
  2. <nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">
  3. ...
  4. </nav>
  5. </body>
垂直菜单 (侧边条)
  1. <body data-spy="scroll" data-target="#myScrollspy" data-offset="15">
  2. <nav class="col-sm-3" id="myScrollspy">
  3. <ul class="nav nav-pills nav-stacked" data-spy="affix" data-offset-top="205">
  4. ...
  5. </nav>
  6. </body>