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" 才能正常工作。
实例
<!-- 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-inverse navbar-fixed-top">...<ul class="nav 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>
通过 JavaScript
手动:
实例
$('body').scrollspy({target: ".navbar"})
Scrollspy Options
Options 可以通过数据属性或 JavaScript 传递。对于数据属性,请将选项名称附加到 data-,如 data-offset=""。
| 名称 | 类型 | 默认 | 描述 | 试一试 |
|---|---|---|---|---|
| offset | number | 10 | 指定计算滚动位置时从顶部偏移的像素数 | 试一试 |
Scrollspy 方法
下表列出了所有可用的 scrollspy 方法。
| 方法 | 描述 | 试一试 |
|---|---|---|
| .scrollspy("refresh") | 在 scrollspy 中添加和删除元素时,可以使用此方法刷新文档 | 试一试 |
Scrollspy 事件
下表列出了所有可用的 scrollspy 事件。
| 事件 | 描述 | 试一试 |
|---|---|---|
| activate.bs.scrollspy | 当 scrollspy 激活新项时发生 | 试一试 |
更多实例
带滚动动画的 Scrollspy
如何将平滑页面滚动添加到同一页面上的锚点:
Smooth scrolling
// Add scrollspy to <body>$('body').scrollspy({target: ".navbar", offset: 50});// Add smooth scrolling on all links inside the navbar$("#myNavbar a").on('click', function(event) {// Make sure this.hash has a value before overriding default behaviorif (this.hash !== "") {// Prevent default anchor click behaviorevent.preventDefault();// Store hashvar hash = this.hash;// Using jQuery's animate() method to add smooth page scroll// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area$('html, body').animate({scrollTop: $(hash).offset().top}, 800, function(){// Add hash (#) to URL when done scrolling (default click behavior)window.location.hash = hash;});} // End if});
Scrollspy & Affix
把 Affix 插件与 Scrollspy 插件一起使用:
水平菜单 (导航条)
<body data-spy="scroll" data-target=".navbar" data-offset="50"><nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">...</nav></body>
垂直菜单 (侧边条)
<body data-spy="scroll" data-target="#myScrollspy" data-offset="15"><nav class="col-sm-3" id="myScrollspy"><ul class="nav nav-pills nav-stacked" data-spy="affix" data-offset-top="205">...</nav></body>