<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery自定义消息提示框</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
/* 消息提示框基础样式 */
.custom-alert {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
min-width: 300px;
max-width: 80%;
padding: 15px 20px;
border-radius: 5px;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
z-index: 9999;
opacity: 0;
transition: opacity 0.3s, top 0.3s;
display: flex;
align-items: center;
justify-content: space-between;
}
/* 不同类型消息的样式 */
.custom-alert-success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.custom-alert-error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.custom-alert-warning {
background-color: #fff3cd;
color: #856404;
border: 1px solid #ffeeba;
}
.custom-alert-info {
background-color: #d1ecf1;
color: #0c5460;
border: 1px solid #bee5eb;
}
/* 关闭按钮样式 */
.custom-alert-close {
margin-left: 15px;
cursor: pointer;
font-weight: bold;
font-size: 18px;
line-height: 1;
}
/* 显示状态 */
.custom-alert-show {
opacity: 1;
top: 30px;
}
</style>
</head>
<body>
<h1>jQuery自定义消息提示框演示</h1>
<button id="btn-success">显示成功消息</button>
<button id="btn-error">显示错误消息</button>
<button id="btn-warning">显示警告消息</button>
<button id="btn-info">显示信息消息</button>
<script>
$(document).ready(function() {
// 自定义消息提示函数
function showAlert(message, type, duration) {
// 默认参数处理
type = type || 'info';
duration = duration || 3000;
// 创建消息元素
var alertElement = $('<div class="custom-alert custom-alert-' + type + '">' +
'<span>' + message + '</span>' +
'<span class="custom-alert-close">×</span>' +
'</div>');
// 添加到body
$('body').append(alertElement);
// 显示动画
setTimeout(function() {
alertElement.addClass('custom-alert-show');
}, 10);
// 关闭按钮事件
alertElement.find('.custom-alert-close').click(function() {
hideAlert(alertElement);
});
// 自动关闭
if (duration > 0) {
setTimeout(function() {
hideAlert(alertElement);
}, duration);
}
}
// 隐藏消息函数
function hideAlert(element) {
element.removeClass('custom-alert-show');
setTimeout(function() {
element.remove();
}, 300);
}
// 绑定按钮事件
$('#btn-success').click(function() {
showAlert('操作成功完成!', 'success');
});
$('#btn-error').click(function() {
showAlert('发生错误,请重试!', 'error');
});
$('#btn-warning').click(function() {
showAlert('警告:此操作不可撤销!', 'warning');
});
$('#btn-info').click(function() {
showAlert('提示:系统将于今晚进行维护。', 'info', 5000);
});
// 全局挂载(可选)
window.showAlert = showAlert;
});
</script>
</body>
</html>
jQuery自定义消息提示框
于 2025-06-25 17:27:58 首次发布