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('show');
}, 10);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => {
document.body.removeChild(toast);
}, 300);
}, duration);
}
配套CSS样式
Toast通知需要基本的样式来确保美观和动画效果:
.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系统,可以考虑以下增强功能:

class Toast {
constructor() {
this.container = document.createElement('div');
this.container.className = 'toast-container';
document.body.appendChild(this.container);
}
show(message, options = {}) {
const { duration = 3000, type = 'default' } = options;
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.textContent = message;
this.container.appendChild(toast);
setTimeout(() => toast.classList.add('show'), 10);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, duration);
}
}
// 使用示例
const toast = new Toast();
toast.show('操作成功', { type: 'success', duration: 2000 });
配套增强CSS
.toast-container {
position: fixed;
bottom: 20px;
left: 0;
right: 0;
display: flex;
flex-direction: column;
align-items: center;
pointer-events: none;
z-index: 1000;
}
.toast {
margin-bottom: 10px;
padding: 12px 24px;
border-radius: 4px;
opacity: 0;
transition: opacity 0.3s ease, transform 0.3s ease;
transform: translateY(20px);
}
.toast.show {
opacity: 1;
transform: translateY(0);
}
.toast-default {
background-color: #333;
color: white;
}
.toast-success {
background-color: #4CAF50;
color: white;
}
.toast-error {
background-color: #F44336;
color: white;
}
注意事项
- 确保Toast不会影响页面其他元素的交互
- 考虑移动端适配,可能需要调整位置和大小
- 对于频繁触发的Toast,需要管理队列避免重叠
- 添加无障碍访问属性如role="alert"提高可访问性
以上实现方案可以根据具体需求进行调整和扩展,如添加图标、进度条或交互按钮等高级功能。






