js实现弹窗的几种方法
使用 alert() 方法
alert() 是最简单的弹窗方法,显示一条消息和一个“确定”按钮。
alert("这是一个警告弹窗");
适用于需要用户确认信息的场景,但无法自定义样式或按钮行为。
使用 confirm() 方法
confirm() 弹窗包含消息、“确定”和“取消”按钮,返回布尔值表示用户选择。
const isConfirmed = confirm("确认执行此操作吗?");
if (isConfirmed) {
console.log("用户点击了确定");
} else {
console.log("用户点击了取消");
}
适合需要用户确认或取消操作的场景。
使用 prompt() 方法
prompt() 弹窗允许用户输入文本,返回输入内容或 null(点击取消)。

const userInput = prompt("请输入您的姓名", "默认值");
if (userInput !== null) {
console.log("输入内容:", userInput);
}
适用于需要用户输入简单信息的场景。
使用 window.open() 方法
通过 window.open() 可以打开一个新窗口或弹窗,支持自定义 URL 和窗口参数。
const popup = window.open(
"https://example.com",
"popupName",
"width=400,height=300"
);
可通过 popup.close() 关闭弹窗。适合需要加载外部页面的场景。

使用 HTML + CSS 自定义弹窗
通过动态创建 DOM 元素实现高度自定义的弹窗。
<div id="customModal" style="display:none; position:fixed; top:20%; left:30%; background:#fff; padding:20px; border:1px solid #000;">
<p>自定义弹窗内容</p>
<button onclick="document.getElementById('customModal').style.display='none'">关闭</button>
</div>
<button onclick="document.getElementById('customModal').style.display='block'">打开弹窗</button>
结合 CSS 和 JavaScript 可实现复杂交互,如动画、表单提交等。
使用第三方库(如 SweetAlert)
SweetAlert 提供美观且功能丰富的弹窗,支持图标、异步操作等。
// 引入 SweetAlert 库后使用
Swal.fire({
title: "成功",
text: "操作已完成",
icon: "success",
confirmButtonText: "确定"
});
适合需要现代化 UI 和高级功能的项目。
注意事项
- 浏览器可能拦截
window.open()触发的弹窗,需确保由用户操作(如点击事件)触发。 - 自定义弹窗需处理无障碍访问(ARIA 属性)和移动端适配。






