滚动监听(Scrollspy)插件,即自动更新导航插件,会根据滚动条的位置自动更新对应的导航目标。其基本的实现是随着您的滚动,基于滚动条的位置向导航栏添加 .active class。
如果您想要单独引用该插件的功能,那么您需要引用 scrollspy.js。或者可以引用 bootstrap.js 或压缩版的 bootstrap.min.js。
创建水平滚动监听,html代码
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 滚动监听(Scrollspy)插件</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<style>
body {
position: relative;
}
.container-fluid2 {
padding-top: 50px;
height: 500px;
color: #fff;
}
p{
font-size:24px;
}
</style>
</head>
<body data-spy="scroll" data-target=".navbar" data-offset="50">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li><a href="#section1">课程1</a></li>
<li><a href="#section2">课程2</a></li>
<li><a href="#section3">课程3</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">课程4<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#section41">课程4-1</a></li>
<li><a href="#section42">课程4-2</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</nav>
<div id="section1" class="container-fluid2" style="background-color: blue; padding-top: 100px;">
<h1>课程1</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! </p>
<p>Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>
<div id="section2" class="container-fluid2" style="background-color: purple;">
<h1>课程2</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! </p>
<p>Try to scroll this section and look at the navigation bar while scrolling! </p>
</div>
<div id="section3" class="container-fluid2" style="background-color:red;">
<h1>课程3</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! </p>
<p>Try to scroll this section and look at the navigation bar while scrolling! </p>
</div>
<div id="section41" class="container-fluid2" style="background-color:green;">
<h1>课程4-1</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! </p>
<p>Try to scroll this section and look at the navigation bar while scrolling! </p>
</div>
<div id="section42" class="container-fluid2" style="background-color: orange;">
<h1>课程4-2</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! </p>
<p>Try to scroll this section and look at the navigation bar while scrolling! </p>
</div>
</body>
</html>
效果图