js实现confirm
使用 window.confirm 实现基础确认框
window.confirm 是浏览器原生提供的对话框方法,接受一个字符串参数作为提示信息,返回布尔值(用户点击“确定”返回 true,点击“取消”返回 false)。
const isConfirmed = confirm('确定要删除此项吗?');
if (isConfirmed) {
console.log('用户确认操作');
} else {
console.log('用户取消操作');
}
自定义样式替代方案(使用模态框)
原生 confirm 无法修改样式,可通过 HTML/CSS 和 JavaScript 模拟自定义确认框:

<div id="customConfirm" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 1px solid #ccc; z-index: 1000;">
<p id="confirmMessage">确定要执行此操作吗?</p>
<button id="confirmYes">确定</button>
<button id="confirmNo">取消</button>
</div>
function showCustomConfirm(message, callback) {
const modal = document.getElementById('customConfirm');
const msgElement = document.getElementById('confirmMessage');
msgElement.textContent = message;
modal.style.display = 'block';
document.getElementById('confirmYes').onclick = function() {
modal.style.display = 'none';
callback(true);
};
document.getElementById('confirmNo').onclick = function() {
modal.style.display = 'none';
callback(false);
};
}
// 调用示例
showCustomConfirm('自定义确认框示例', (result) => {
console.log(result ? '用户确认' : '用户取消');
});
使用第三方库(如 SweetAlert2)
SweetAlert2 提供美观且功能丰富的弹窗,支持异步操作和自定义配置:
安装库:

npm install sweetalert2
代码示例:
import Swal from 'sweetalert2';
Swal.fire({
title: '确认操作',
text: '确定要提交吗?',
icon: 'question',
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消'
}).then((result) => {
if (result.isConfirmed) {
console.log('用户确认');
}
});
异步场景处理
若需在异步操作前确认,可通过 Promise 或 async/await 实现:
async function deleteItem() {
const isConfirmed = await new Promise((resolve) => {
showCustomConfirm('删除后无法恢复', resolve);
});
if (isConfirmed) {
await fetch('/api/delete', { method: 'DELETE' });
}
}
注意事项
- 原生
confirm会阻塞线程,直到用户响应,可能影响用户体验。 - 自定义模态框需处理无障碍访问(ARIA 属性)和遮罩层。
- 第三方库如 SweetAlert2 适合复杂场景,但会增加项目体积。






