js实现弹出
使用 alert 弹出提示框
最简单的弹出方式是使用 alert 方法,直接显示一段文本信息。
alert("这是一个提示信息");
使用 confirm 弹出确认框
confirm 方法会显示一个带有“确定”和“取消”按钮的对话框,并返回用户的选择结果(布尔值)。
const isConfirmed = confirm("你确定要执行此操作吗?");
if (isConfirmed) {
console.log("用户点击了确定");
} else {
console.log("用户点击了取消");
}
使用 prompt 弹出输入框
prompt 方法显示一个对话框,用户可以输入内容,输入的内容会作为返回值返回。
const userInput = prompt("请输入你的名字", "默认值");
if (userInput !== null) {
console.log("用户输入:", userInput);
} else {
console.log("用户取消了输入");
}
自定义模态框(Modal)
通过 HTML 和 CSS 结合 JavaScript 实现更灵活的弹出框。
HTML 结构
<div id="customModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>这是一个自定义模态框</p>
</div>
</div>
CSS 样式
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
cursor: pointer;
}
JavaScript 控制逻辑
const modal = document.getElementById("customModal");
const closeBtn = document.querySelector(".close");
// 打开模态框
function openModal() {
modal.style.display = "block";
}
// 关闭模态框
function closeModal() {
modal.style.display = "none";
}
// 点击关闭按钮或模态框外部关闭
closeBtn.addEventListener("click", closeModal);
window.addEventListener("click", (event) => {
if (event.target === modal) {
closeModal();
}
});
// 调用打开模态框
openModal();
使用第三方库(如 SweetAlert)
SweetAlert 提供了更美观且功能丰富的弹出框。
安装 SweetAlert
npm install sweetalert
使用示例

import Swal from 'sweetalert';
Swal.fire({
title: "提示",
text: "操作成功!",
icon: "success",
confirmButtonText: "确定"
});
总结
- 原生方法:
alert、confirm、prompt适合简单场景。 - 自定义模态框:适合需要高度定制化的需求。
- 第三方库(如 SweetAlert):提供更丰富的交互和样式,适合复杂场景。






