監測滾動條 ScrollSpy

 

在單頁設計中,我們常會把整個頁面分成幾個區塊,

然後在上方或側邊選單中以這些區塊的標題來做為選單項目。

而當我們點選選單項目時,頁面會自動跳到該區塊,

而選單項目會反白或反黑。反過來如果藉由滑鼠捲動到該區塊時

(即該區塊佔了螢幕高度一定比例的大小) ,

該區塊的選單項目也會自動反白。這個效果就稱為「 ScrollSpy 」。

<!DOCTYPE html>
<html>
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
  #section1 {padding-top:50px;height:500px;color: #fff; background-color: #1E88E5;}
  #section2 {padding-top:50px;height:500px;color: #fff; background-color: #673ab7;}
  #section3 {padding-top:50px;height:500px;color: #fff; background-color: #ff9800;}
  #section41 {padding-top:50px;height:500px;color: #fff; background-color: #00bcd4;}
  #section42 {padding-top:50px;height:500px;color: #fff; background-color: #009688;}
  </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">Section 1</a></li>
          <li><a href="#section2">Section 2</a></li>
          <li><a href="#section3">Section 3</a></li>
          <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Section 4 <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#section41">Section 4-1</a></li>
              <li><a href="#section42">Section 4-2</a></li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </div>
</nav>    

<div id="section1" class="container-fluid">
  <h1>Section 1</h1>
</div>
<div id="section2" class="container-fluid">
  <h1>Section 2</h1>
</div>
<div id="section3" class="container-fluid">
  <h1>Section 3</h1>
</div>
<div id="section41" class="container-fluid">
  <h1>Section 4 Submenu 1</h1>
</div>
<div id="section42" class="container-fluid">
  <h1>Section 4 Submenu 2</h1>
</div>

</body>
</html>

 

參考資料:

25 Websites with Scrollspy Navigation for Your Inspiration

bootstrap scrollspy

thesmart/jquery-scrollspy

sxalexander/jquery-scrollspy

DD ScrollSpy Menu v1.2

pascaldevink/scrollspy.js