如何使用 Bootstrap 建立多步進度條?


進度指示器是任務進度的一種視覺表示,通常以水平條的形式呈現,隨著任務的進行而填充。當要執行的任務包含一系列子任務或階段時,多階段進度指示器非常有用。本文將指導您使用 Bootstrap(一個廣泛使用的前端 Web 開發框架)建立多階段進度條。學習完本教程後,您將瞭解如何為 Web 應用程式建立美觀且功能強大的進度條。

方法

我們將採用一種相當簡單的方法來實現上述目標。我們從 HTML 程式碼開始,這將為進度條和按鈕奠定基礎,使用 Bootstrap 的進度條和按鈕元件。我們將使用內聯樣式屬性將進度條的寬度初始化為 0%。我們將透過向 HTML 新增“role”、“aria-valuenow”、“aria-valuemin”和“aria-valuemax”屬性來增強網站的可訪問性。

然後,我們將使用 Bootstrap 按鈕元件中的“btn”類建立按鈕,每個按鈕都具有不同的 ID,以便稍後在 jQuery 程式碼中識別。藉助 jQuery 程式設計,我們將為每個按鈕設定事件處理程式,以便單擊按鈕時可以相應地更改進度條的寬度和值。

將透過定義 .progress-bar 類的寬度 CSS 屬性來實現寬度的修改,而值將透過定義 aria-valuenow 屬性來修改。這種方法提供了一種簡單而靈活的方法來建立動態的多階段進度指示器,可以根據使用者活動更改進度狀態。Bootstrap 和 jQuery 的結合提供了一種簡單的方法來建立美觀且實用的進度指示器,只需少量程式碼。

示例

以下是我們將在此示例中檢視的完整程式碼:

<!DOCTYPE html>
<html>
<head>
   <title>How to create multi step progress bar using Bootstrap?</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <style>
      .progress {
         height: 20px;
      }
   </style>
</head>
<body>
   <h4>How to create multi step progress bar using Bootstrap?</h4>
   <div class="container">
      <div class="progress">
         <div class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0"  aria-valuemin="0"
         aria-valuemax="100"></div>
      </div>
      <br>
      <div class="btn-group" role="group">
         <button type="button" class="btn btn-success" id="step1">Step 1</button>
         <button type="button" class="btn btn-info" id="step2">Step 2</button>
         <button type="button" class="btn btn-warning" id="step3">Step 3</button>
         <button type="button" class="btn btn-danger" id="step4">Step 4</button>
      </div>
   </div>
   <script>
      $(document).ready(function() {
         let currentStep = 0;
         $("#step1").click(function() {
            currentStep = 25;
            $(".progress-bar").css("width", currentStep + "%").attr("aria-valuenow", currentStep);
         });
         $("#step2").click(function() {
            currentStep = 50;
            $(".progress-bar").css("width", currentStep + "%").attr("aria-valuenow", currentStep);
         });
         $("#step3").click(function() {
            currentStep = 75;
            $(".progress-bar").css("width", currentStep + "%").attr("aria-valuenow", currentStep);
         });
         $("#step4").click(function() {
            currentStep = 100;
            $(".progress-bar").css("width", currentStep + "%").attr("aria-valuenow", currentStep);
         });
      });
   </script>
</body>
</html>

結論

總而言之,使用 Bootstrap 建立多階段進度條是一種簡單的方法,可以極大地改善使用者對 Web 應用程式的體驗。按照本文中的指導,您將能夠建立一個引人注目且完全可操作的進度條,準確地顯示任務的進度。無論您是經驗豐富的 Web 開發人員還是新手,使用 Bootstrap 建立多階段進度條都是一項寶貴的技能,對您的工作非常有益。因此,不要延遲,立即運用您新獲得的技能並建立一個多階段進度條!

更新於:2023年4月10日

1K+ 瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.