如何創建:警告消息
學習如何使用 CSS 創建警告消息。
警告
警告消息可用于通知用戶一些特殊事項:危險、成功、信息或警告。
×
危險!表示危險或可能產生負面影響的操作。
×
成功!表示成功或積極的操作。
×
信息!表示中性的信息更改或操作。
×
警告!表示可能需要注意的警告。
創建警告消息
第一步 - 添加 HTML:
<div class="alert"> <span class="closebtn" onclick="this.parentElement.style.display='none';">×</span> This is an alert box. </div>
如果您希望能夠關閉警告消息,請添加一個帶有 onclick
屬性的 <span>
元素,該屬性表示“當您單擊我時,隱藏我的父元素” - 即容器 <div class="alert">
。
提示:使用 HTML 實體 "×" 創建字母 "x"。
第二步 - 添加 CSS:
設置警告框和關閉按鈕的樣式:
/* 警告消息框 */ .alert { padding: 20px; background-color: #f44336; /* Red */ color: white; margin-bottom: 15px; } /* 關閉按鈕 */ .closebtn { margin-left: 15px; color: white; font-weight: bold; float: right; font-size: 22px; line-height: 20px; cursor: pointer; transition: 0.3s; } /* 當鼠標移動到關閉按鈕上時 */ .closebtn:hover { color: black; }
多個警告
如果頁面上有多個警告消息,您可以添加以下腳本,以在不使用每個 <span>
元素的 onclick
屬性的情況下關閉不同的警告。
并且,如果您希望點擊警告時它們緩慢淡出,請將不透明度和過渡添加到 alert
類中:
實例
<style> .alert { opacity: 1; transition: opacity 0.6s; /* 600 毫秒淡出 */ } </style> <script> // 獲取所有 class="closebtn" 的元素 var close = document.getElementsByClassName("closebtn"); var i; // 循環遍歷所有關閉按鈕 Loop through all close buttons for (i = 0; i < close.length; i++) { // 遍歷所有關閉按鈕 close[i].onclick = function(){ // 獲取<span class="closebtn">的父元素(<div class="alert">) var div = this.parentElement; // 設置 div 的不透明度為 0(透明) div.style.opacity = "0"; // 600 毫秒后隱藏 div(與淡出所需的時間相同) setTimeout(function(){ div.style.display = "none"; }, 600); } } </script>
相關頁面
教程:如何創建便簽