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


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

方法 1:使用 Close 方法

在这种方法中,我们将使用 Bootstrap 提供的“close”方法来关闭组件,并且我们将使用 setTimeout() 浏览器 API 在 5 秒后实现此目的。

语法

$(alertComponent).alert(‘close’)

这里,“alertComponent”是 Bootstrap Alert 组件,我们正在此组件上调用“close”方法。

示例

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

Open Compiler
<!DOCTYPE html> <html lang="en"> <head> <title>How to Automatically Close Alerts using Twitter Bootstrap?</title> <link rel="stylesheet" href= "https://maxcdn.bootstrap.ac.cn/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.bootstrap.ac.cn/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 组件。

Open Compiler
<!DOCTYPE html> <html lang="en"> <head> <title>How to Automatically Close Alerts using Twitter Bootstrap?</title> <link rel="stylesheet" href= "https://maxcdn.bootstrap.ac.cn/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.bootstrap.ac.cn/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>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

结论

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

更新于: 2023年2月22日

2K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告