Bootstrap Scrollspy source code learning

  • 2021-07-24 10:05:51
  • OfStack

In this article, we share the specific code of Bootstrap Scrollspy plug-in for your reference. The specific contents are as follows

Navigation bar Scrollspy example


<!-- 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" rel="external nofollow" rel="external nofollow" >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>

Vertical Scrollspy example


<body data-spy="scroll" data-target="#myScrollspy" data-offset="20">

 <div class="container">
 <div class="row">
  <nav class="col-sm-3" id="myScrollspy">
  <ul class="nav nav-pills nav-stacked">
   <li><a href="#section1" rel="external nofollow" rel="external nofollow" >Section 1</a></li>
   ...
  </ul>
  </nav>
  <div class="col-sm-9">
  <div id="section1"> 
   <h1>Section 1</h1>
   <p>Try to scroll this page and look at the navigation list while scrolling!</p>
  </div> 
  ...
  </div>
 </div>
 </div>

</body>


Use of Scrollspy

Using Scrollspy requires only a few key attributes to be added to the corresponding HTML element:
-data-spy= "scroll"
Add to elements that need to be scrolled, such as the most common body element, or container.
-data-target= "selector"
Added to the elements to be scrolled, selector indicates the elements that control scrolling, such as ". navbar", "# myScrollspy".
- < a href= "# section" > section < /a >
Link to the corresponding position with link in the element that controls scrolling. Note that the linked id should match the id of the corresponding location element. For example, < div id = "section1" > And < a href= "# seciton1".


Related articles: