toast实现 js
Toast 实现(JavaScript)
Toast 是一种轻量级的通知消息,通常在用户操作后短暂显示。以下是几种实现方式:
使用纯 JavaScript 和 CSS
创建基本的 HTML 结构:
<div id="toast" class="toast-hidden">Toast Message</div>
添加 CSS 样式:
#toast {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
padding: 12px 24px;
border-radius: 4px;
background-color: #333;
color: white;
opacity: 0;
transition: opacity 0.3s ease;
}
.toast-visible {
opacity: 1;
}
JavaScript 实现:
function showToast(message, duration = 3000) {
const toast = document.getElementById('toast');
toast.textContent = message;
toast.classList.add('toast-visible');
setTimeout(() => {
toast.classList.remove('toast-visible');
}, duration);
}
使用第三方库
Materialize CSS 实现:
M.toast({html: 'Toast message', displayLength: 4000});
Bootstrap 实现:
var toastEl = document.getElementById('toast');
var toast = new bootstrap.Toast(toastEl);
toast.show();
动态创建 Toast
更灵活的创建方式:
function createToast(message, options = {}) {
const defaultOptions = {
duration: 3000,
position: 'bottom-center',
type: 'info'
};
const config = {...defaultOptions, ...options};
const toast = document.createElement('div');
toast.className = `toast toast-${config.type}`;
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.remove();
}, config.duration);
}
动画效果增强
添加入场和出场动画:

function animatedToast(message) {
const toast = document.createElement('div');
toast.className = 'toast-animated';
toast.textContent = message;
document.body.appendChild(toast);
// 入场动画
setTimeout(() => {
toast.style.transform = 'translateY(0)';
toast.style.opacity = '1';
}, 10);
// 出场动画
setTimeout(() => {
toast.style.transform = 'translateY(100px)';
toast.style.opacity = '0';
setTimeout(() => {
toast.remove();
}, 300);
}, 3000);
}
这些实现方法可以根据具体需求进行调整和扩展,添加更多自定义功能如多种消息类型、可关闭按钮等。






