📅  最后修改于: 2023-12-03 15:01:41.863000             🧑  作者: Mango
本文介绍如何使用 JavaScript 和 HTML 制作动画样式的警报消息框。该消息框可用于网站的提示、警告、成功或错误等信息展示。
<div class="alert alert-success">
<div class="alert-icon">
<i class="fa fa-check-circle"></i>
</div>
<div class="alert-message">
<b>Success:</b> Your operation completed successfully.
</div>
</div>
以上是警报消息框的 HTML 结构,使用 <div>
元素、Font Awesome 图标和文本内容进行构建。CSS 样式表也已预置了一些基本样式。
使用 JavaScript 技术,添加了一个名为 showAlert()
的函数,该函数可以为警报消息框添加 CSS 类,并以动画形式显示出来。这是由 setTimeout()
函数来实现的。同时,添加了一个 hideAlert()
函数,它可以将警报框隐藏起来。
// 获取警报框元素
var alertBox = document.querySelector('.alert');
// 显示警报框动画效果
function showAlert() {
alertBox.classList.add('alert-show');
setTimeout(function(){
alertBox.classList.remove('alert-show');
}, 5000);
}
// 隐藏警报框
function hideAlert() {
alertBox.classList.remove('alert-show');
}
下面是警报框的样式代码:
/* Alert box */
.alert {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
font-size: 14px;
}
.alert-icon {
float: left;
margin-right: 10px;
}
.alert-message {
margin-left: 50px;
}
.alert-show {
animation: slideinout 5s linear;
-webkit-animation: slideinout 5s linear;
}
@keyframes slideinout {
0% {
transform: translateX(-100%);
}
12.5%, 87.5% {
transform: translateX(0%);
}
100% {
transform: translateX(100%);
}
}
@-webkit-keyframes slideinout {
0% {
-webkit-transform: translateX(-100%);
}
12.5%, 87.5% {
-webkit-transform: translateX(0%);
}
100% {
-webkit-transform: translateX(100%);
}
}
/* Alert box colors */
.alert-success {
background-color: #d4edda;
border-color: #c3e6cb;
color: #155724;
}
.alert-danger {
background-color: #f8d7da;
border-color: #f5c6cb;
color: #721c24;
}
.alert-warning {
background-color: #fff3cd;
border-color: #ffeeba;
color: #856404;
}
.alert-info {
background-color: #cce5ff;
border-color: #b8daff;
color: #0c5460;
}
上述代码演示了如何使用 JavaScript 和 HTML 制作动画警报消息框。你可以通过对代码进行调整,更改样式和动画效果以适应自己的特定应用场景。