JSFiddle - React, Tailwind, and code Playground
HTML
<h1 style="text-align: center;">JavaScript 系列三:練習1 ── alert 示警元件</h1>
<div class="alert alert-primary">
歡迎您點擊「抖內」按鈕,以實際行動支持我們。
<button class="btn-close">×</button>
</div>
<hr>
<div class="alert alert-success">
您已成功下訂單!以下為您的訂單詳細資訊。
<button class="btn-close">×</button>
</div>
<hr>
<div class="alert alert-danger">
抱歉,系統發生錯誤,請稍後重新嘗試。
<button class="btn-close">×</button>
</div>
<hr>
<div class="alert alert-warning">
請注意,以下內容包含「劇透」爆雷資訊。
<button class="btn-close">×</button>
</div>
CSS
* {
padding: 0;
margin: 0;
}
.alert {
width: 95%;
box-sizing: border-box;
padding: 10px 50px;
display: flex;
align-items: center;
justify-content: space-between;
margin: 10px auto;
font-weight: 900;
border-top: 3px solid;
}
.btn-close {
font-size: 24px;
margin: 0;
height: 25px;
line-height: 25px;
width: 25px;
box-sizing: border-box;
border-radius: 0;
border: 1px solid transparent;
cursor: pointer;
background-color: transparent;
}
.alert-primary {
background-color: #bee3f8;
color: #3956da;
border-color: #3956da;
}
.alert-success {
background-color: #c6f6d5;
color: #266c4e;
border-color: #266c4e;
}
.alert-danger {
background-color: #fed7d7;
color: #c81e1e;
border-color: #c81e1e;
}
.alert-warning {
background-color: #feebc8;
color: #8e4a10;
border-color: #8e4a10;
}
.alert-primary .btn-close {
color: #3956da;
}
.alert-success .btn-close {
color: #266c4e;
}
.alert-danger .btn-close {
color: #c81e1e;
}
.alert-warning .btn-close {
color: #8e4a10;
}
.alert-primary .btn-close:hover,
.alert-success .btn-close:hover,
.alert-danger .btn-close:hover,
.alert-warning .btn-close:hover {
color: #000;
}
JavaScript
let closeBtns = document.querySelectorAll(".btn-close");
for (let closeBtn of closeBtns) {
closeBtn.onclick = close;
}
function close() {
let closeBtn = event.target;
closeBtn.closest(".alert").remove();
}