js实现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('fade-out');
setTimeout(() => toast.remove(), 500);
}, duration);
}
// CSS样式建议
.toast-notification {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: rgba(0,0,0,0.7);
color: white;
padding: 12px 24px;
border-radius: 4px;
animation: fade-in 0.5s;
}
.fade-out {
opacity: 0;
transition: opacity 0.5s;
}
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
使用第三方库
对于更复杂的需求,可以考虑成熟的Toast库:
-
Toastr - 简单易用的通知库
// 引入CDN或npm安装后 toastr.success('操作成功'); toastr.error('发生错误'); -
SweetAlert2 - 功能丰富的弹窗库
Swal.fire({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000, title: '自定义Toast' });
使用浏览器原生API
现代浏览器支持Notification API,适合系统级通知:
if ('Notification' in window) {
Notification.requestPermission().then(perm => {
if (perm === 'granted') {
new Notification('标题', { body: '消息内容' });
}
});
}
注意事项

- 移动端适配需要考虑不同屏幕尺寸
- 多个Toast出现时建议实现队列管理
- 可添加进度条显示剩余时间
- 支持自定义位置(top/bottom/center等)






