如何使用 Bootstrap 创建多级进度条?

bootstrapweb developmentfront end technology

进度指示器是对任务进展的直观描述,通常表现为随着任务进展而填充的进度条。当正在执行的任务包含一系列小任务或阶段时,多级进度指示器非常有用。在本文中,我们将指导您使用 Bootstrap(一个广泛使用的前端 Web 开发框架)创建多层进度条。完成本指南后,您将对如何创建美观且易于操作的进度条有深入的理解,并将其应用于您的 Web 应用程序中。

方法

我们将采用一种相当简单的方法来实现上述目标。我们的旅程从 HTML 代码开始,它将利用 Bootstrap 的进度条和按钮组件为进度条和按钮奠定基础。我们将使用内联样式属性将进度条的宽度初始化为 0%。我们将通过在 HTML 中添加"role"、"aria-valuenow"、"aria-valuemin"和"aria-valuemax"属性来增强网站的可访问性。

然后,我们将使用 Bootstrap 按钮组件中的"btn"类创建按钮,并为每个按钮分配一个不同的标识符,以便稍后在 jQuery 代码中识别。借助 jQuery 编程,我们将为每个按钮设置事件处理程序,以便在点击按钮时相应地调整进度条的宽度和大小。

宽度的修改可以通过定义 .progress-bar 类的 width 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 创建多阶段进度条都是一项宝贵的技能,可以极大地促进您的项目。因此,不要犹豫,立即运用您新学到的技能,创建一个多阶段进度条!


相关文章