警报

创建于 2024-12-03 / 24
字体: [默认] [大] [更大]

了解如何使用 CSS 创建警报消息。


警报

警报消息可用于通知用户一些特殊情况:危险、成功、信息或警告。

× Danger! Indicates a dangerous or potentially negative action. × Success! Indicates a successful or positive action. × Info! Indicates a neutral informative change or action. × Warning! Indicates a warning that might need attention.

亲自试一试 »


创建警报消息

步骤 1) 添加 HTML:

实例

<div class="alert">
  <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
  This is an alert box.
</div>

如果您希望能够关闭警报消息,请添加一个带有 onclick 属性的 <span> 元素,该属性显示"当您点击我时,隐藏我的父元素" ; - 这是容器 <div> (class="alert")。

提示:使用 HTML 实体 "&times;" 创建字母 "x"。



步骤 2) 添加 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 属性。

而且,如果您希望警报在单击它们时慢慢淡出,请添加 opacitytransition 到 alert 类:

实例

<style>
.alert {
  opacity: 1;
  transition: opacity 0.6s; /* 600ms 淡出 */
}
</style>

<script>
// Get all elements with 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(){

    // Get the parent of <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>
亲自试一试 »

提示: 另请查看 Notes



0 人点赞过