js实现alert
使用 alert 方法显示弹窗
在 JavaScript 中,alert 是浏览器提供的全局方法,用于显示一个简单的弹窗对话框。弹窗内容为传入的字符串参数,用户需要点击“确定”按钮才能关闭弹窗。
alert("这是一个提示信息");
自定义弹窗样式
如果需要更灵活的弹窗(如自定义样式或交互),可以通过 HTML 和 CSS 实现,并用 JavaScript 控制显示/隐藏。
<div id="customAlert" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 1px solid #ccc; box-shadow: 0 0 10px rgba(0,0,0,0.1);">
<p id="alertMessage">默认提示信息</p>
<button onclick="document.getElementById('customAlert').style.display = 'none'">确定</button>
</div>
<script>
function showCustomAlert(message) {
document.getElementById("alertMessage").textContent = message;
document.getElementById("customAlert").style.display = "block";
}
</script>
使用第三方库实现高级弹窗
对于更复杂的弹窗需求(如动画、按钮回调等),可以使用第三方库如 SweetAlert2:
-
引入 SweetAlert2 库:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> -
调用弹窗:
Swal.fire({ title: "提示", text: "这是一个更美观的弹窗", icon: "success" });
注意事项
alert会阻塞浏览器线程,直到用户点击确认。- 过度使用
alert可能影响用户体验,建议仅在必要场景(如关键错误提示)使用。 - 移动端浏览器可能对
alert的样式和行为有特殊限制。







