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 创建更灵活的弹窗:
- 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.4); } .modal-content { background-color: #fefefe; margin: 15% auto; padding: 20px; width: 80%; } .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"; } };
### 使用第三方库(如 SweetAlert)
引入 SweetAlert2 库实现美观弹窗:
1. 安装库
```bash
npm install sweetalert2
- 使用示例
import Swal from 'sweetalert2';
Swal.fire({ title: "成功", text: "操作已完成", icon: "success", confirmButtonText: "确定" });

### 注意事项
- 内置弹窗(`alert`、`confirm`、`prompt`)会阻塞线程,直到用户响应。
- 自定义弹窗需处理可访问性和动画效果以提升用户体验。
- 第三方库(如 SweetAlert)提供更多定制选项,但会增加项目体积。






