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);
}
自定义弹框(使用 HTML 和 CSS)
如果需要更灵活的弹框,可以通过 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: #fff;
margin: 15% auto;
padding: 20px;
width: 50%;
border-radius: 5px;
}
.close {
float: right;
cursor: pointer;
}
JavaScript 控制

const modal = document.getElementById("customModal");
const closeBtn = document.querySelector(".close");
// 打开弹框
function openModal() {
modal.style.display = "block";
}
// 关闭弹框
closeBtn.onclick = function() {
modal.style.display = "none";
};
// 点击弹框外部关闭
window.onclick = function(event) {
if (event.target === modal) {
modal.style.display = "none";
}
};
使用第三方库(如 SweetAlert2)
SweetAlert2 提供美观且功能丰富的弹框,比原生弹框更灵活。
安装 SweetAlert2
npm install sweetalert2
使用示例
import Swal from 'sweetalert2';
Swal.fire({
title: "提示",
text: "操作成功!",
icon: "success",
confirmButtonText: "确定"
});
总结
- 简单弹框:
alert()、confirm()、prompt()。 - 自定义弹框:通过 HTML、CSS 和 JavaScript 实现。
- 高级弹框:使用第三方库如 SweetAlert2。






