toast实现 js
实现 Toast 通知的 JavaScript 方法
Toast 通知是一种短暂出现的提示消息,通常用于显示操作结果或状态更新。以下是实现 Toast 的几种方法:
使用纯 JavaScript 实现
创建一个简单的 Toast 函数,动态生成 DOM 元素并控制显示与隐藏:
function showToast(message, duration = 3000) {
const toast = document.createElement('div');
toast.className = 'toast-notification';
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.classList.add('show');
}, 10);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => document.body.removeChild(toast), 300);
}, duration);
}
对应 CSS 样式:

.toast-notification {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background-color: #333;
color: white;
padding: 12px 24px;
border-radius: 4px;
opacity: 0;
transition: opacity 0.3s ease;
}
.toast-notification.show {
opacity: 1;
}
使用第三方库
流行的 Toast 通知库可以简化实现:
-
Toastr:

<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script> <script> toastr.success('操作成功'); toastr.error('发生错误'); </script> -
SweetAlert2:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> <script> Swal.fire({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000, title: '提示消息' }); </script>
高级定制选项
对于更复杂的 Toast 系统,可以添加以下功能:
function showAdvancedToast(options) {
const defaults = {
message: '',
type: 'info', // info, success, warning, error
duration: 3000,
position: 'bottom-center' // top-left, top-center, top-right, etc.
};
const config = {...defaults, ...options};
// 实现逻辑...
}
动画效果增强
使用 CSS 动画创建更丰富的入场和退场效果:
@keyframes slideIn {
from { transform: translateY(100%); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
.toast-notification {
animation: slideIn 0.3s ease forwards;
}
.toast-notification.hide {
animation: fadeOut 0.3s ease forwards;
}






