js alert实现
使用 alert() 函数实现弹窗
alert() 是 JavaScript 中最简单的弹窗方法,用于向用户显示一条消息。它会在浏览器中弹出一个模态对话框,用户需要点击“确定”按钮才能继续操作。
语法:
alert("要显示的消息");
示例:
alert("Hello, World!");
自定义弹窗样式
如果需要更复杂的弹窗样式,可以通过 HTML 和 CSS 自定义一个弹窗,然后使用 JavaScript 控制其显示和隐藏。
HTML 结构:

<div id="customAlert" style="display: none;">
<div class="alert-content">
<p id="alertMessage"></p>
<button onclick="closeAlert()">确定</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-color: white;
padding: 20px;
border-radius: 5px;
text-align: center;
}
JavaScript 控制:
function showAlert(message) {
document.getElementById("alertMessage").textContent = message;
document.getElementById("customAlert").style.display = "flex";
}
function closeAlert() {
document.getElementById("customAlert").style.display = "none";
}
使用第三方库实现弹窗
可以使用诸如 SweetAlert2 这样的第三方库来创建更美观、功能更丰富的弹窗。

安装 SweetAlert2:
npm install sweetalert2
使用示例:
import Swal from 'sweetalert2';
Swal.fire({
title: '提示',
text: '这是一个更美观的弹窗',
icon: 'info',
confirmButtonText: '确定'
});
注意事项
alert() 会阻塞 JavaScript 的执行,直到用户点击确定按钮。这在某些情况下可能会导致不良的用户体验。
自定义弹窗或使用第三方库可以提供更好的用户体验,但需要更多的代码和资源。






