js实现确认
使用 confirm 方法实现确认框
JavaScript 提供了 confirm 方法,用于显示一个带有确认和取消按钮的对话框。用户点击确认返回 true,点击取消返回 false。
const result = confirm("确定要执行此操作吗?");
if (result) {
console.log("用户点击了确认");
} else {
console.log("用户点击了取消");
}
自定义确认弹窗
通过 HTML 和 CSS 创建一个自定义确认弹窗,提升用户体验。
<div id="customConfirm" style="display: none;">
<div class="confirm-box">
<p>确定要删除吗?</p>
<button id="confirmBtn">确认</button>
<button id="cancelBtn">取消</button>
</div>
</div>
function showCustomConfirm(message, onConfirm, onCancel) {
const confirmBox = document.getElementById("customConfirm");
confirmBox.style.display = "block";
document.getElementById("confirmBtn").onclick = () => {
confirmBox.style.display = "none";
onConfirm();
};
document.getElementById("cancelBtn").onclick = () => {
confirmBox.style.display = "none";
onCancel();
};
}
showCustomConfirm(
"确定要删除吗?",
() => console.log("用户确认"),
() => console.log("用户取消")
);
使用 Promise 封装确认逻辑
通过 Promise 可以更灵活地处理异步确认操作。
function asyncConfirm(message) {
return new Promise((resolve) => {
const result = confirm(message);
resolve(result);
});
}
asyncConfirm("确定继续吗?").then((confirmed) => {
if (confirmed) {
console.log("继续操作");
} else {
console.log("取消操作");
}
});
结合第三方库实现高级确认框
使用如 SweetAlert2 等库可以创建更美观的确认弹窗。

import Swal from "sweetalert2";
Swal.fire({
title: "确认删除?",
text: "删除后无法恢复",
icon: "warning",
showCancelButton: true,
confirmButtonText: "确认",
cancelButtonText: "取消",
}).then((result) => {
if (result.isConfirmed) {
console.log("删除成功");
}
});
注意事项
- 浏览器原生
confirm会阻塞代码执行,直到用户响应。 - 自定义弹窗需确保无障碍访问,如添加
aria属性和键盘事件支持。 - 第三方库需引入相关依赖,但能节省开发时间。






