如何使用 Twitter Bootstrap 自动关闭警报?

bootstrapweb developmentfront end technology

我们可以使用 Twitter Bootstrap 提供的"close"方法和"hide"类自动关闭 Bootstrap 警报组件。 Twitter Bootstrap Alert 组件用于向用户显示带有消息的警报,通常用于响应用户操作或事件。

方法 1:使用 Close 方法

在此方法中,我们将使用 Bootstrap 提供的"close"方法关闭组件,并使用 setTimeout() 浏览器 API 在 5 秒后关闭组件。

语法

$(alertComponent).alert('close')

此处,"alertComponent"是 Bootstrap Alert 组件,我们将在此组件上调用"close"方法。

示例

在此示例中,我们将使用 Bootstrap 提供的"close"方法和 setTimeout() 浏览器 API 在 5 秒后自动关闭 Alert 组件。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>How to Automatically Close Alerts using Twitter Bootstrap?</title>
   <link rel="stylesheet" href=
   "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
   <script src=
      "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js">
   </script>
   <!-- Including Bootstrap JS -->
   <script src=
      "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js">
   </script>
</head>
<body>
   <h3>How to Automatically Close Alerts using Twitter Bootstrap?</h3>
   <div id="alert" class="alert alert-success">
   This alert will automatically close in 5 seconds.
   </div>
   <script>
      const alert = document.getElementById('alert');
      setTimeout(() => {
         $('#alert').alert('close')
      }, 5000)
   </script>
</body>
</html>

方法 2:使用 Hide 类

在此方法中,我们将向 Alert 组件添加一个"hide"类,以自动关闭 Alert,并使用 setTimeout() 浏览器 API 在 5 秒后实现此目的。

语法

$(alertComponent).addClass(hide')

此处,"alertComponent"是 Bootstrap Alert 组件,我们将在此组件上添加"hide"类。

示例

在此示例中,我们将使用 Bootstrap 提供的"hide"类和 setTimeout() 浏览器 API 在 5 秒后自动关闭 Alert 组件。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>How to Automatically Close Alerts using Twitter Bootstrap?</title>
   <link rel="stylesheet" href=
   "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
   <script src=
      "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js">
   </script>
   <!-- Including Bootstrap JS -->
   <script src=
      "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js">
   </script>
</head>
<body>
   <h3>How to Automatically Close Alerts using Twitter Bootstrap?</h3>
   <div id="alert" class="alert alert-success">
      This alert will automatically close in 5 seconds.
   </div>
   <script>
      const alert = document.getElementById('alert');
      setTimeout(() => {
         $('#alert').addClass('hide')
      }, 5000)
   </script>
</body>
</html>

总结

在本文中,我们学习了如何使用 Twitter Bootstrap 自动关闭 Alert 组件,具体方法有两种。第一种方法,我们使用了"close"方法;第二种方法,我们使用了 Bootstrap 提供的"hide"类。


相关文章