js实现toast
实现Toast的基本方法
使用纯JavaScript实现Toast通知可以通过动态创建DOM元素并添加动画效果来完成。以下是一个简单的实现方式:
function showToast(message, duration = 3000) {
const toast = document.createElement('div');
toast.className = 'toast';
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需要配合CSS样式才能正常显示和动画效果:
.toast {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background-color: rgba(0, 0, 0, 0.7);
color: white;
padding: 12px 24px;
border-radius: 4px;
opacity: 0;
transition: opacity 0.3s ease;
z-index: 9999;
}
.toast.show {
opacity: 1;
}
使用示例
调用showToast函数即可显示通知:
showToast('操作成功', 2000);
高级实现选项
可以扩展基础功能实现更多特性:
function showToast(options) {
const defaults = {
message: '',
duration: 3000,
position: 'bottom',
type: 'default'
};
const config = {...defaults, ...options};
const toast = document.createElement('div');
toast.className = `toast toast-${config.position} toast-${config.type}`;
toast.textContent = config.message;
document.body.appendChild(toast);
setTimeout(() => toast.classList.add('show'), 10);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => document.body.removeChild(toast), 300);
}, config.duration);
}
对应的扩展CSS
.toast-top {
top: 20px;
bottom: auto;
}
.toast-center {
top: 50%;
bottom: auto;
transform: translate(-50%, -50%);
}
.toast-success {
background-color: #4CAF50;
}
.toast-error {
background-color: #F44336;
}
.toast-warning {
background-color: #FF9800;
}
使用第三方库
如果需要更复杂的功能,可以考虑使用现成的Toast库:
- Toastr: https://github.com/CodeSeven/toastr
- SweetAlert: https://sweetalert2.github.io/
- iziToast: https://izitoast.marcelodolza.com/







