js实现弹窗报警
使用 alert() 方法实现弹窗报警
JavaScript 提供了 alert() 方法,可以快速实现弹窗报警功能。该方法会显示一个带有指定消息和“确定”按钮的模态对话框。
alert("这是一个报警弹窗!");
使用 confirm() 方法实现确认弹窗
如果需要用户确认操作,可以使用 confirm() 方法。它会显示一个带有指定消息、“确定”和“取消”按钮的对话框,并返回布尔值表示用户的选择。
const userConfirmed = confirm("你确定要执行此操作吗?");
if (userConfirmed) {
console.log("用户点击了确定");
} else {
console.log("用户点击了取消");
}
使用 prompt() 方法获取用户输入
prompt() 方法可以显示一个对话框,提示用户输入文本。它返回用户输入的字符串,如果用户取消则返回 null。
const userName = prompt("请输入你的名字:", "默认名字");
if (userName !== null) {
console.log(`用户输入的名字是:${userName}`);
}
自定义弹窗样式
如果需要更灵活的弹窗样式,可以通过 HTML 和 CSS 创建自定义弹窗,然后用 JavaScript 控制显示和隐藏。

HTML 部分:
<div id="customAlert" style="display:none;">
<div class="alert-content">
<p id="alertMessage">这是自定义报警消息</p>
<button onclick="closeCustomAlert()">确定</button>
</div>
</div>
CSS 部分:
#customAlert {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
}
.alert-content {
background: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.3);
}
JavaScript 部分:

function showCustomAlert(message) {
document.getElementById('alertMessage').textContent = message;
document.getElementById('customAlert').style.display = 'flex';
}
function closeCustomAlert() {
document.getElementById('customAlert').style.display = 'none';
}
// 使用示例
showCustomAlert("这是一个自定义报警弹窗!");
使用第三方库实现高级弹窗
对于更复杂的需求,可以考虑使用第三方库如 SweetAlert2,它提供了美观且功能丰富的弹窗解决方案。
安装 SweetAlert2:
npm install sweetalert2
使用示例:
import Swal from 'sweetalert2';
Swal.fire({
title: '报警!',
text: '这是一个高级报警弹窗',
icon: 'warning',
confirmButtonText: '确定'
});






