如何使用 CSS 和 JavaScript 创建 Snackbar/Toast 提示框?
如果你想向用户显示任何信息的通知,例如购买产品的优惠券,你可以创建一个 Snackbar 提示框。将其用作弹出窗口,以在屏幕底部显示消息。通常,Snackbar 提示框会在一段时间后消失。Snackbar 提示框会淡入,并在一段时间后淡出。让我们看看如何通过单击按钮使用 CSS 和 JavaScript 创建 Snackbar 提示框。
创建 Snackbar 提示框按钮
为了使 Snackbar 提示框出现,你需要点击一个按钮。使用`
<button class="snackBtn">Show Snackbar</button> <h2>Click on the above button to see snackbar message</h2>
设置 Snackbar 提示框文本
单击 Snackbar 按钮时出现的 Snackbar 文本:
<div class="snackText">Apply the coupon code AMIT15 to get 15% Off.</div>
设置 Snackbar 提示框文本样式
Snackbar 默认情况下是隐藏的,并且在单击按钮时出现。因此,将文本的 visibility 属性设置为 hidden。此外,使用 position 属性和 fixed 值设置固定位置:
.snackText {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: rgb(110, 26, 106);
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
left: 50%;
bottom: 30px;
font-size: 17px;
}
脚本
以下是使 Snackbar 提示框出现然后消失的脚本。单击按钮后,Snackbar 提示框将出现,并在 3 秒后消失。我们在这里设置了 3000 毫秒,即 3 秒:
<script>
document
.querySelector(".snackBtn")
.addEventListener("click", showSnackBar);
function showSnackBar() {
var x = document.querySelector(".snackText");
x.className += " show";
setTimeout(function() {
x.className = x.className.replace("show", "");
}, 3000);
}
</script>
显示 snacktext
我们上面已经将 snacktext 设置为不可见,但是单击按钮后它将出现。为实现此目的,我们将 visibility 属性设置为 visible:
.snackText.show {
visibility: visible;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
示例
要使用 CSS 和 JavaScript 创建 Snackbar/Toast 提示框,代码如下:
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.snackText {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: rgb(110, 26, 106);
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
left: 50%;
bottom: 30px;
font-size: 17px;
}
.snackBtn {
border: none;
padding: 10px;
font-size: 18px;
background-color: rgb(92, 0, 128);
color: white;
}
.snackText.show {
visibility: visible;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
@keyframes fadein {
from {
bottom: 0;
opacity: 0;
}
to {
bottom: 30px;
opacity: 1;
}
}
@keyframes fadeout {
from {
bottom: 30px;
opacity: 1;
}
to {
bottom: 0;
opacity: 0;
}
}
</style>
</head>
<body>
<h1>Snackbar / Toast Example</h1>
<button class="snackBtn">Show Snackbar</button>
<h2>Click on the above button to see snackbar message</h2>
<div class="snackText">Apply the coupon code AMIT15 to get 15% Off.</div>
<script>
document
.querySelector(".snackBtn")
.addEventListener("click", showSnackBar);
function showSnackBar() {
var x = document.querySelector(".snackText");
x.className += " show";
setTimeout(function() {
x.className = x.className.replace("show", "");
}, 3000);
}
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP