Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo Snackbar / Toast với CSS và JavaScript

Snackbar/Toast là thông báo nhỏ hiện ra rồi tự mất sau vài giây.

Ví dụ

<!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 Example</h1> <button class="snackBtn">Hiện Snackbar</button> <h2>Nhấn nút để xem thông báo snackbar</h2> <div class="snackText">Một số văn bản thông báo..</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>

Kết quả

Thông báo trượt lên từ dưới, hiển thị 3 giây rồi mờ dần biến mất.