效果图
正常
警告
错误
HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>简易 Toast 消息提示</title>
<style>
.toast {
min-width: 160px;
color: #fff;
text-align: center;
border-radius: 4px;
padding: 12px 20px;
position: fixed;
z-index: 9999;
left: 50%;
top: 10%;
transform: translateX(-50%);
opacity: 1;
transition: opacity 0.5s, transform 0.5s;
font-size: 14px;
}
.toast-success {
background-color: #aa55ff;
}
.toast-warning {
background-color: #ff9800;
}
.toast-error {
background-color: #f44336;
}
</style>
</head>
<body>
<h2>点击按钮显示带类型的消息提示</h2>
<button onclick="showToast('操作成功', 'success')">成功提示</button>
<button onclick="showToast('请检查输入', 'warning')">警告提示</button>
<button onclick="showToast('系统错误', 'error')">错误提示</button>
<script>
function showToast(message, type = 'info', duration = 2000) {
const toast = document.createElement('div');
toast.textContent = message;
toast.classList.add('toast');
// 根据类型添加新的类名
switch (type.toLowerCase()) {
case 'success':
toast.classList.add('toast-success');
break;
case 'warning':
toast.classList.add('toast-warning');
break;
case 'error':
toast.classList.add('toast-error');
break;
default:
toast.classList.add('toast-success'); // 默认为 success
break;
}
// 添加到 body 中
document.body.appendChild(toast);
// 设置定时隐藏
setTimeout(() => {
if (document.body.contains(toast)) {
document.body.removeChild(toast);
}
}, duration);
}
</script>
</body>
</html>