js实现弹窗报警
使用 alert() 方法实现弹窗报警
alert() 是 JavaScript 中最简单的弹窗方法,用于显示一条消息和一个“确定”按钮。
语法:
alert("这里是报警信息");
示例:
alert("系统检测到异常操作!");
使用 confirm() 方法实现确认弹窗
confirm() 弹窗包含“确定”和“取消”按钮,适合需要用户确认的场景。
语法:
confirm("确认执行此操作吗?");
示例:
if (confirm("确定删除该文件吗?")) {
console.log("用户确认删除");
} else {
console.log("用户取消操作");
}
使用 prompt() 方法实现输入弹窗
prompt() 弹窗允许用户输入内容,适合需要用户提供信息的场景。
语法:
prompt("请输入您的姓名:", "默认值");
示例:
const userName = prompt("请输入用户名:");
if (userName) {
console.log("用户输入:", userName);
}
自定义弹窗样式(HTML/CSS)
通过 HTML 和 CSS 创建自定义弹窗,灵活性更高。
HTML 结构:
<div id="customAlert" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>这是自定义报警弹窗!</p>
</div>
</div>
CSS 样式:
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
cursor: pointer;
}
JavaScript 控制:
const modal = document.getElementById("customAlert");
const span = document.getElementsByClassName("close")[0];
// 显示弹窗
function showAlert() {
modal.style.display = "block";
}
// 关闭弹窗
span.onclick = function() {
modal.style.display = "none";
};
// 点击外部关闭弹窗
window.onclick = function(event) {
if (event.target === modal) {
modal.style.display = "none";
}
};
使用第三方库(如 SweetAlert2)
SweetAlert2 提供美观且功能丰富的弹窗,适合复杂需求。
安装:
npm install sweetalert2
使用示例:
import Swal from 'sweetalert2';
Swal.fire({
title: '报警!',
text: '检测到未授权访问',
icon: 'error',
confirmButtonText: '确定'
});
监听事件触发弹窗
通过事件监听(如点击、键盘输入)触发弹窗。
示例:

document.getElementById("alertButton").addEventListener("click", function() {
alert("按钮被点击,触发报警!");
});






