Bootstrap JS Scrollspy
JS Scrollspy (scrollspy.js)
O plugin Scrollspy é usado para atualizar automaticamente os links em uma lista de navegação com base na posição de rolagem.
Para um tutorial sobre Scrollspy, leia nosso Tutorial Bootstrap Scrollspy .
Dica: O plugin Scrollspy é frequentemente usado em conjunto com o plugin Affix .
Via dados-* Atributos
Adicione data-spy="scroll"
ao elemento que deve ser usado como área de rolagem (geralmente esse é o <body>
elemento).
Em seguida, adicione o data-target
atributo com um valor do id ou o nome da classe da barra de navegação ( .navbar
). Isso é para garantir que a barra de navegação esteja conectada à área rolável.
Observe que os elementos roláveis devem corresponder ao ID dos links dentro dos itens da lista da barra de navegação ( <div id="section1">
matches <a href="#section1">
).
O atributo opcional data-offset
especifica o número de pixels a serem deslocados do topo ao calcular a posição de rolagem. Isso é útil quando você sente que os links dentro da barra de navegação alteram o estado ativo muito cedo ou muito cedo ao pular para os elementos roláveis. O padrão é 10 pixels.
Requer posicionamento relativo: O elemento com data-spy="scroll" requer a propriedade position CSS , com um valor de "relative" para funcionar corretamente.
Exemplo
<!-- 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>
Por JavaScript
Ative manualmente com:
Exemplo
$('body').scrollspy({target: ".navbar"})
Opções do Scrollspy
As opções podem ser passadas por meio de atributos de dados ou JavaScript. Para atributos de dados, anexe o nome da opção a data-, como em 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 |
Métodos Scrollspy
A tabela a seguir lista todos os métodos scrollspy disponíveis.
Method | Description | Try it |
---|---|---|
.scrollspy("refresh") | When adding and removing elements from the scrollspy, this method can be used to refresh the document |
Eventos Scrollspy
A tabela a seguir lista todos os eventos scrollspy disponíveis.
Event | Description | Try it |
---|---|---|
activate.bs.scrollspy | Occurs when a new item becomes activated by the scrollspy |
Mais exemplos
Scrollspy com rolagem animada
Como adicionar uma rolagem de página suave a uma âncora na mesma página:
Rolagem suave
// 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 behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var 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 & Afixo
Usando o plugin Affix junto com o plugin Scrollspy:
Menu horizontal (barra de navegação)
<body data-spy="scroll" data-target=".navbar" data-offset="50">
<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">
...
</nav>
</body>
Menu Vertical (Sidenav)
<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>