如何使用 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 元件。
<!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”類。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP