Wie man erstellt: Snackbar / Toast
- Vorherige Seite Responsive Floating
- Nächste Seite Vollbildfenster
Lernen Sie, wie Sie Snackbar/Toast mit CSS und JavaScript erstellen.
Snackbar / Toast
Snackbar werden in der Regel als Tooltips/Pop-up-Fenster verwendet, um Nachrichten am unteren Bildschirmrand anzuzeigen.
Klicken Sie auf die Schaltfläche, um den Snackbar anzuzeigen. Er verschwindet nach 3 Sekunden.
Snackbar erstellen
Schritt 1 - Fügen Sie HTML hinzu:
<!-- Snackbar mit dem Button öffnen --> <button onclick="myFunction()">Snackbar anzeigen</button> <!-- Echtzeit snackbar --> <div id="snackbar">Einige Text einige Nachricht..</div>
Schritt 2 - Fügen Sie CSS hinzu:
Stellen Sie den Stil des snackbar ein und fügen Sie Animationen hinzu:
/* snackbar - Positionierung am unteren Bildschirmrand und in der Mitte */ #snackbar { visibility: hidden; /* Standardmäßig versteckt, wird sichtbar, wenn geklickt */ min-width: 250px; /* Standardmäßige Mindestbreite gesetzt */ margin-left: -125px; /* Den Wert von min-width durch 2 geteilt */ background-color: #333; /* Schwarzer Hintergrund */ color: #fff; /* Weißer Textfarbe */ text-align: center; /* Text zentriert */ border-radius: 2px; /* Eckenrundung */ padding: 16px; /* 内边距 */ position: fixed; /* 固定在屏幕顶部 */ z-index: 1; /* 如果需要,添加z-index */ left: 50%; /* 将snackbar居中 */ bottom: 30px; /* 距离底部 30px */ } /* 单击按钮时显示 snackbar(使用 JavaScript 添加的类) */ #snackbar.show { visibility: visible; /* Show the snackbar */ /* 添加动画:用0.5秒淡入和淡出 snackbar。但是,将淡出过程延迟 2.5 秒。 */ -webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s; animation: fadein 0.5s, fadeout 0.5s 2.5s; } /* 淡入和淡出 snackbar 的动画 */ @-webkit-keyframes fadein { from {bottom: 0; opacity: 0;} to {bottom: 30px; opacity: 1;} } @keyframes fadein { from {bottom: 0; opacity: 0;} to {bottom: 30px; opacity: 1;} } @-webkit-keyframes fadeout { from {bottom: 30px; opacity: 1;} to {bottom: 0; opacity: 0;} } @keyframes fadeout { from {bottom: 30px; opacity: 1;} to {bottom: 0; opacity: 0;} }
第三步 - 添加 JavaScript:
使用 JavaScript 通过点击按钮向 snackbar 容器添加 "show" 类:
function myFunction() { // 获取 snackbar DIV var x = document.getElementById("snackbar"); // 向 DIV 添加 "show" 类 x.className = "show"; // 3秒后,从 DIV 中删除 "show" 类 setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000); }
- Vorherige Seite Responsive Floating
- Nächste Seite Vollbildfenster