JSFiddle - React, Tailwind, and code Playground
HTML
<!-- JavaScript 系列三:練習2 ── toast 吐司元件 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./index.css">
<title>Document</title>
</head>
<body>
<div id="container">
<button class="btn" onclick="toastSuccess()">成功訂購商品</button>
<hr>
<button class="btn" onclick="toastError()">訂購商品失敗</button>
<div class="toast1">
訂購成功!可以查看 Email 確認訂單細節!
</div>
<div class="toast2">
抱歉,訂購失敗!請稍後重新嘗試
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
CSS
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
.btn {
display: block;
font-size: 18px;
background-color: #14375e;
color: white;
border: 1px solid #14375e;
border-radius: 5px;
padding: 5px;
margin: 30px;
cursor: pointer;
}
.toast1,
.toast2 {
font-size: 24px;
border: 1px solid black;
padding-top: 33px;
width: 480px;
height: 100px;
text-align: center;
align-items: center;
color: white;
visibility: hidden;
position: fixed;
bottom: 30px;
right: 0%;
}
.toast1.success {
visibility: visible;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
background-color: darkgreen;
}
.toast2.error {
visibility: visible;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
background-color: darkred;
}
/* Animations to fade the snackbar in and out */
@keyframes fadein {
from {
bottom: 0;
opacity: 0;
}
to {
bottom: 30px;
opacity: 1;
}
}
@keyframes fadein {
from {
bottom: 0;
opacity: 0;
}
to {
bottom: 30px;
opacity: 1;
}
}
@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
function toastSuccess() {
var x = document.querySelector('.toast1');
x.classList.add('success')
setTimeout(function () {
x.classList.remove('success');
}, 3000);
}
function toastError() {
var x = document.querySelector('.toast2');
x.classList.add('error');
setTimeout(function () {
x.classList.remove('error');
}, 3000);
}