以下是使用 jQuery 实现提示框确认取消功能的完整指南:
<div id="confirmBox" class="dialog">
<div class="dialog-content">
<p class="message"></p>
<button class="confirm-btn">确认</button>
<button class="cancel-btn">取消</button>
</div>
</div>
通过动态修改 .message
内容实现多场景复用
.dialog {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 300px;
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
z-index: 9999;
display: none;
}
.dialog-content {
padding: 20px;
text-align: center;
}
button {
margin: 10px;
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.confirm-btn {
background: #4CAF50;
color: white;
}
标准化样式设计,支持主题色定制
function showConfirm(options) {
const $box = $('#confirmBox');
// 初始化内容
$box.find('.message').text(options.message || '确认操作?');
// 显示弹窗
$box.fadeIn(200);
// 确认回调
$box.find('.confirm-btn').off('click').on('click', function() {
options.onConfirm && options.onConfirm();
$box.fadeOut(200);
});
// 取消回调
$box.find('.cancel-btn').off('click').on('click', function() {
options.onCancel && options.onCancel();
$box.fadeOut(200);
});
}
// 使用示例
$('#deleteBtn').click(function() {
showConfirm({
message: '确定要删除该记录吗?',
onConfirm: function() {
// 执行删除操作
console.log('已删除');
},
onCancel: function() {
console.log('操作取消');
}
});
});
封装可复用函数,支持自定义回调
// 在关闭按钮点击时增加确认
$('.dialog').on('click', '.close-btn', function(e) {
e.stopPropagation();
if (confirm('确定要关闭吗?')) {
$('#confirmBox').hide();
}
});
防止用户误触关闭弹窗
function loadDynamicContent(url) {
$.get(url, function(html) {
$('#confirmBox .dialog-content').html(html);
});
}
支持从服务器加载自定义内容
// 添加滑动动画
$('#confirmBox').hide().fadeIn(300).delay(2000).slideUp(300);
提升用户体验的动画方案
<!DOCTYPE html>
<html>
<head>
<title>确认弹窗示例</title>
<style>
/* 上述CSS样式 */
</style>
</head>
<body>
<button id="deleteBtn">删除数据</button>
<div id="confirmBox" class="dialog">
<div class="dialog-content">
<p class="message"></p>
<button class="confirm-btn">确认</button>
<button class="cancel-btn">取消</button>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 上述jQuery代码
</script>
</body>
</html>
console.log
验证回调触发顺序debugger
语句进行断点调试没有搜到相关的文章