js实现弹窗的几种方法
使用 alert() 方法
alert() 是最简单的弹窗方法,用于显示一条消息和一个确认按钮。
alert("这是一个警告弹窗");
使用 confirm() 方法
confirm() 弹窗包含确认和取消按钮,返回一个布尔值表示用户的选择。
const result = confirm("你确定要删除吗?");
if (result) {
console.log("用户点击了确认");
} else {
console.log("用户点击了取消");
}
使用 prompt() 方法
prompt() 弹窗允许用户输入文本,返回输入的字符串或 null(用户取消)。
const name = prompt("请输入你的名字", "默认名字");
if (name !== null) {
console.log("输入的名字是:" + name);
}
使用 window.open() 方法
window.open() 可以打开一个新窗口或标签页,模拟弹窗效果。
const popup = window.open("", "弹窗标题", "width=400,height=300");
if (popup) {
popup.document.write("<h1>这是一个弹窗</h1>");
}
使用自定义 HTML 弹窗
通过 HTML 和 CSS 创建自定义弹窗,结合 JavaScript 控制显示和隐藏。
<div id="customModal" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 1px solid black;">
<p>这是一个自定义弹窗</p>
<button onclick="document.getElementById('customModal').style.display = 'none'">关闭</button>
</div>
<script>
function showModal() {
document.getElementById("customModal").style.display = "block";
}
</script>
<button onclick="showModal()">打开自定义弹窗</button>
使用第三方库(如 SweetAlert)
SweetAlert 提供了更美观、功能丰富的弹窗,支持图标、动画等。
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
title: "成功!",
text: "操作已完成",
icon: "success",
confirmButtonText: "确定"
});
</script>
使用 <dialog> 元素(HTML5)
HTML5 的 <dialog> 元素提供原生弹窗支持,可通过 JavaScript 控制。

<dialog id="dialog">
<p>这是一个原生弹窗</p>
<button onclick="document.getElementById('dialog').close()">关闭</button>
</dialog>
<script>
document.getElementById("dialog").showModal();
</script>






