如何使用 CSS 和 JavaScript 建立滾動指示器?


滾動指示器會根據情況顯示和動畫。當捲軸向下滾動時,進度條會顯示還剩餘多少元素。當捲軸滾動到底部時,滾動指示器(即進度條)也結束。讓我們看看如何使用 CSS 和 JavaScript 建立滾動指示器。

固定頭部

首先,使用 `position` 屬性和 `fixed` 值將頁首的位置設定為固定。即使網頁滾動到底部,頁首也會保持固定狀態。

.header {
   position: fixed;
   top: 0;
   margin-bottom: 100px;
   z-index: 1;
   width: 100%;
   background-color: #ebfffd;
}

建立進度條

對於滾動指示器,使用進度條。

<div class="progressContainer">
   <div class="progressBar"></div>
</div>

設定進度條樣式

設定進度條容器的寬度和高度。容器寬度設定為 100%。

.progressContainer {
   width: 100%;
   height: 20px;
   background: #ccc;
}

初始進度條

進度條的初始寬度設定為 0%,因為網頁載入時位於頂部。

.progressBar {
   height: 20px;
   background: #724caf;
   width: 0%;
}

設定內容的 div

對於網頁上的內容,建立一個 div。

<div class="content">
   <h2>Some headers</h2>
   <h2>Some headers</h2>
   <h2>Some headers</h2>
   <h2>Some headers</h2>
   <h2>Some headers</h2>
</div>

示例

要使用 CSS 和 JavaScript 建立滾動指示器,程式碼如下:

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-size: 28px;
         margin:0px;
         padding:0px;
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      }
      .header {
         position: fixed;
         top: 0;
         margin-bottom: 100px;
         z-index: 1;
         width: 100%;
         background-color: #ebfffd;
      }
      .progressContainer {
         width: 100%;
         height: 20px;
         background: #ccc;
      }
      .progressBar {
         height: 20px;
         background: #724caf;
         width: 0%;
      }
      .content {
         padding: 100px 0;
         margin: 50px auto 0 auto;
         width: 80%;
      }
   </style>
</head>
<body>
   <div class="header">
      <h1>Scroll indicator example</h1>
      <div class="progressContainer">
         <div class="progressBar"></div>
      </div>
   </div>
   <div class="content">
      <h2>Some headers</h2>
      <h2>Some headers</h2>
      <h2>Some headers</h2>
      <h2>Some headers</h2>
      <h2>Some headers</h2>
   </div>
   <script>
      window.onscroll = function() {showProgress()};
      function showProgress() {
         var scrollCalculate = document.body.scrollTop || document.documentElement.scrollTop;
         var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
         var scrolled = (scrollCalculate / height) * 100;
      document.querySelector(".progressBar").style.width = scrolled + "%";
      }
   </script>
</body>
</html>

更新於:2023-12-14

342 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告