如何使用 CSS 和 JavaScript 创建 snackbar/toast?
cssweb developmentfront end technologyjavascript
要使用 CSS 和 JavaScript 创建 snackbar/toast,代码如下 −
示例
<!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">Show Snackbar</button> <h2>Click on the above button to see snackbar message</h2> <div class="snackText">Some text some message..</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"按钮 −