js实现弹框
使用 alert 实现简单弹框
JavaScript 的 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);
}
自定义 HTML 弹框
通过 DOM 操作创建自定义弹框,灵活控制样式和交互:
<div id="customModal" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 1px solid #ccc;">
<p>这是一个自定义弹框</p>
<button onclick="closeModal()">关闭</button>
</div>
<script>
function showModal() {
document.getElementById("customModal").style.display = "block";
}
function closeModal() {
document.getElementById("customModal").style.display = "none";
}
</script>
<button onclick="showModal()">打开弹框</button>
使用第三方库(如 SweetAlert)
SweetAlert 提供美观的弹框,支持图标、异步操作等:

- 引入库:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> - 示例代码:
Swal.fire({ title: "成功!", text: "操作已完成", icon: "success", confirmButtonText: "确定" });
监听弹框关闭事件
适用于需要回调的场景,如自定义弹框或第三方库:
Swal.fire({
title: "提示",
text: "5秒后自动关闭",
timer: 5000
}).then((result) => {
if (result.dismiss === Swal.DismissReason.timer) {
console.log("弹框因超时关闭");
}
});
弹框动画效果
通过 CSS 添加动画增强用户体验:
.modal-animation {
animation: fadeIn 0.3s;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
将 modal-animation 类添加到自定义弹框元素即可。
以上方法覆盖了从原生到自定义的弹框实现,可根据需求选择合适方案。






