現代 Web 應用需要美觀、無障礙、可複用的提示彈出層。本文基於原始碼重構,採用 CSS3 動畫、BEM 命名、語意化 HTML、ARIA 屬性、ES6 類別封裝,打造生產級 Toast/Modal 元件。
<div class="toast-container" role="region" aria-live="polite" aria-label="系統通知">
<div class="toast toast--success" role="alert">
<div class="toast__icon" aria-hidden="true">
<svg viewBox="0 0 24 24" width="24" height="24">
<path fill="currentColor" d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/>
</svg>
</div>
<div class="toast__content">
<h4 class="toast__title">操作成功</h4>
<p class="toast__message">您的資料已儲存</p>
</div>
<button class="toast__close" aria-label="關閉通知">×</button>
</div>
</div>
<!-- 觸發按鈕 -->
<button id="show-toast" class="btn btn--primary">顯示成功提示</button>
:root {
--toast-duration: 300ms;
--toast-easing: cubic-bezier(0.4, 0, 0.2, 1);
--toast-bg: #fff;
--toast-radius: 8px;
--toast-shadow: 0 4px 20px rgba(0,0,0,0.15);
}
.toast-container {
position: fixed;
top: 20px;
right: 20px;
z-index: 9999;
display: flex;
flex-direction: column;
gap: 12px;
pointer-events: none; /* 穿透容器,只讓 toast 接收事件 */
}
.toast {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 16px 16px 16px 12px;
min-width: 300px;
max-width: 450px;
background: var(--toast-bg);
border-radius: var(--toast-radius);
box-shadow: var(--toast-shadow);
pointer-events: auto; /* 恢復 toast 本身事件 */
animation: slideIn var(--toast-duration) var(--toast-easing);
opacity: 0; /* 初始隱藏,JS 控制顯示 */
}
.toast--enter {
animation: slideIn var(--toast-duration) var(--toast-easing) forwards;
}
.toast--leave {
animation: slideOut var(--toast-duration) var(--toast-easing) forwards;
}
@keyframes slideIn {
from { opacity: 0; transform: translateX(100%); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes slideOut {
from { opacity: 1; transform: translateX(0); }
to { opacity: 0; transform: translateX(100%); }
}
/* 類型變體 */
.toast--success .toast__icon { color: #28a745; }
.toast--error .toast__icon { color: #dc3545; }
.toast--warning .toast__icon { color: #ffc107; }
.toast--info .toast__icon { color: #17a2b8; }
.toast__icon { flex-shrink: 0; margin-top: 2px; }
.toast__content { flex: 1; min-width: 0; }
.toast__title { margin: 0 0 4px; font-size: 1rem; font-weight: 600; }
.toast__message { margin: 0; font-size: 0.875rem; color: #666; line-height: 1.4; }
.toast__close {
background: none; border: none; font-size: 1.25rem; line-height: 1;
color: #999; cursor: pointer; padding: 0 4px; flex-shrink: 0;
}
.toast__close:hover { color: #333; }
/* 響應式 */
@media (max-width: 480px) {
.toast-container { left: 12px; right: 12px; top: auto; bottom: 12px; }
.toast { min-width: 0; }
}
class ToastManager {
constructor(containerSelector = '.toast-container') {
this.container = document.querySelector(containerSelector) || this.createContainer();
this.toasts = new Map(); // id -> { element, timer }
this.idCounter = 0;
}
createContainer() {
const container = document.createElement('div');
container.className = 'toast-container';
container.setAttribute('role', 'region');
container.setAttribute('aria-live', 'polite');
container.setAttribute('aria-label', '系統通知');
document.body.appendChild(container);
return container;
}
show(options) {
const {
type = 'info',
title = '',
message = '',
duration = 5000,
closable = true,
onClose
} = options;
const id = ++this.idCounter;
const toast = this.createToastElement(id, type, title, message, closable);
// 進場動畫
requestAnimationFrame(() => {
toast.classList.add('toast--enter');
});
this.container.appendChild(toast);
// 自動關閉計時器
let timer = null;
if (duration > 0) {
timer = setTimeout(() => this.hide(id), duration);
}
// 關閉按鈕事件
const closeBtn = toast.querySelector('.toast__close');
if (closeBtn) {
closeBtn.addEventListener('click', () => this.hide(id));
}
// 滑鼠懸停暫停計時
if (duration > 0) {
toast.addEventListener('mouseenter', () => clearTimeout(timer));
toast.addEventListener('mouseleave', () => {
timer = setTimeout(() => this.hide(id), duration);
});
}
this.toasts.set(id, { element: toast, timer, onClose });
return id;
}
createToastElement(id, type, title, message, closable) {
const toast = document.createElement('div');
toast.className = `toast toast--${type}`;
toast.dataset.toastId = id;
toast.role = 'alert';
toast.innerHTML = `
${title ? `${this.escapeHtml(title)}
` : ''}
${message ? `` : ''}
${closable ? '' : ''}
`;
return toast;
}
getIconSVG(type) {
const icons = {
success: '',
error: '',
warning: '',
info: ''
};
return icons[type] || icons.info;
}
hide(id) {
const record = this.toasts.get(id);
if (!record) return;
const { element, timer, onClose } = record;
clearTimeout(timer);
// 離場動畫
element.classList.remove('toast--enter');
element.classList.add('toast--leave');
// 動畫結束後移除 DOM
element.addEventListener('animationend', () => {
element.remove();
this.toasts.delete(id);
onClose?.();
}, { once: true });
}
hideAll() {
for (const id of this.toasts.keys()) {
this.hide(id);
}
}
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
}
// 全域單例
window.toast = new ToastManager();
// 使用範例
document.getElementById('show-toast').addEventListener('click', () => {
window.toast.show({
type: 'success',
title: '操作成功',
message: '您的資料已成功儲存,3 秒後自動關閉',
duration: 3000
});
});
// 掛載便利方法
['success', 'error', 'warning', 'info'].forEach(type => {
ToastManager.prototype[type] = function(title, message, options = {}) {
return this.show({ ...options, type, title, message });
};
});
// 使用更簡潔
toast.success('儲存成功', '資料已同步至雲端');
toast.error('刪除失敗', '網路錯誤,請重試', { duration: 0 }); // 不自動關閉
toast.warning('存儲空間不足', '建議清理舊檔案');
toast.info('新功能上線', '點擊查看詳情', {
onClose: () => console.log('用戶關閉了資訊提示')
});
role="region" aria-live="polite":螢幕閱讀器會朗讀新增內容role="alert":重要通知立即打斷朗讀aria-label:關閉按鈕無障礙名稱從簡單的 jQuery toggleClass 進化為現代化 Toast 元件,關鍵在於:
這樣的元件才能在大型專案中長期維護、擴展並提供一致體驗。