js 实现弹窗
使用 alert 方法实现简单弹窗
alert 是浏览器内置的弹窗方法,用于显示一条消息和一个确认按钮。
alert('这是一个简单的弹窗');
使用 confirm 方法实现确认弹窗
confirm 弹窗包含消息、确认和取消按钮,返回布尔值(确认为 true,取消为 false)。
const isConfirmed = confirm('确定要执行此操作吗?');
if (isConfirmed) {
console.log('用户点击了确认');
} else {
console.log('用户点击了取消');
}
使用 prompt 方法实现输入弹窗
prompt 弹窗允许用户输入内容,返回输入的字符串(取消则返回 null)。
const userInput = prompt('请输入您的名字:');
if (userInput !== null) {
console.log('用户输入:', userInput);
}
自定义 HTML 弹窗
通过 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%;
}
.close {
float: right;
cursor: pointer;
}
JavaScript 控制逻辑

const modal = document.getElementById('customModal');
const closeBtn = document.querySelector('.close');
// 显示弹窗
function showModal() {
modal.style.display = 'block';
}
// 关闭弹窗
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
});
// 点击弹窗外部关闭
window.addEventListener('click', (event) => {
if (event.target === modal) {
modal.style.display = 'none';
}
});
使用第三方库(如 SweetAlert)
SweetAlert 提供美观且功能丰富的弹窗,需引入库文件后调用。
引入 SweetAlert
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
示例代码
Swal.fire({
title: '提示',
text: '操作成功!',
icon: 'success',
confirmButtonText: '确定'
});
注意事项
- 浏览器原生弹窗(
alert、confirm、prompt)会阻塞页面交互,建议谨慎使用。 - 自定义弹窗或第三方库更适合复杂场景,提供更好的用户体验。






