js3-2
by wang_siang
HTML
<main>
<button onclick="toastSuccess()">成功訂購商品</button>
<hr>
<button onclick="toastError()">訂購商品失敗</button>
<section class="bottom-bolck">
</section>
</main>
CSS
* {
box-sizing: border-box;
}
main {
width: 502px;
margin: 0px auto;
}
main .toast {
font-size: 20px;
font-weight: 600;
list-style: none;
padding: 32px 26px;
border-radius: 12px;
color: #ffffff;
display: flex;
gap: 24px;
box-shadow: 0 0 8px 2px rgb(219, 219, 219);
align-items: center;
opacity: 0;
transform: translateX(100px);
transition: opacity 0.5s ease-out, transform 0.5s ease-out;
}
.toast.show {
opacity: 1;
transform: translateX(0);
}
.toast.hide {
opacity: 0;
}
main .bottom-bolck {
width: 502px;
margin-top: 40px;
position: fixed;
bottom: 20px;
display: flex;
flex-direction: column;
justify-content: end;
gap: 18px;
}
.icon {
width: 36px;
height: 36px;
}
.toast-error {
background-color: rgb(250, 68, 27);
}
.toast-success {
background: rgb(66, 214, 135);
}
JavaScript
const bottomBolck = document.querySelector('.bottom-bolck');
function toastSuccess() {
const div = document.createElement('div');
const span = document.createElement('span');
if (bottomBolck.children.length + 1 <= 3) {
bottomBolck.append(div);
div.append(span);
div.classList.add('toast', 'toast-success');
div.insertAdjacentHTML("afterbegin", `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" stroke-width="0" fill="#ffffff"
stroke="currentColor" class="icon">
<path
d="M256 48a208 208 0 1 1 0 416 208 208 0 1 1 0-416zm0 464A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM369 209c9.4-9.4 9.4-24.6 0-33.9s-24.6-9.4-33.9 0l-111 111-47-47c-9.4-9.4-24.6-9.4-33.9 0s-9.4 24.6 0 33.9l64 64c9.4 9.4 24.6 9.4 33.9 0L369 209z">
</path>
</svg>
`);
span.textContent = '訂購成功!可以查看 Email 確認訂單細節!';
setTimeout(() => { div.classList.add('show') }, 100);
setTimeout(() => {
div.classList.add('hide');
setTimeout(() => { div.remove() }, 500);
}, 3000);
return;
}
}
function toastError() {
const div = document.createElement('div');
const span = document.createElement('span');
if (bottomBolck.children.length + 1 <= 3) {
bottomBolck.append(div);
div.append(span);
div.classList.add('toast', 'toast-error');
div.insertAdjacentHTML('afterbegin', ` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" stroke-width="0" fill="#ffffff"
stroke="currentColor" class="icon">
<path
d="M256 48a208 208 0 1 1 0 416 208 208 0 1 1 0-416zm0 464A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM175 175c-9.4 9.4-9.4 24.6 0 33.9l47 47-47 47c-9.4 9.4-9.4 24.6 0 33.9s24.6 9.4 33.9 0l47-47 47 47c9.4 9.4 24.6 9.4 33.9 0s9.4-24.6 0-33.9l-47-47 47-47c9.4-9.4 9.4-24.6 0-33.9s-24.6-9.4-33.9 0l-47 47-47-47c-9.4-9.4-24.6-9.4-33.9 0z">
</path>
</svg>`)
...