ตัวอย่าง
Snackbar หรือ Toast คือข้อความแจ้งเตือนชั่วคราวที่แสดงที่มุมล่างของหน้าจอ ให้ใช้ CSS animation และ JavaScript setTimeout เพื่อควบคุมการแสดงผล
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<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</h1>
<button class="snackBtn">แสดง Snackbar</button>
<h2>คลิกปุ่มด้านบนเพื่อดูข้อความ snackbar</h2>
<div class="snackText">ข้อความตัวอย่างบางอย่าง..</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>
ผลลัพธ์
โค้ดข้างต้นจะสร้างผลลัพธ์ดังนี้:

เมื่อคลิกปุ่ม “แสดง Snackbar”:
