點擊文章標題時顯示「Loading...」動畫,能給使用者即時回饋,緩解等待焦慮。本文從原始 jQuery 實作出發,重構為現代、無障礙、效能優化的版本。
// utils/loading-link.js
export function enhanceArticleLinks(selector = '.entry-title a') {
document.querySelectorAll(selector).forEach(link => {
if (link.dataset.enhanced) return; // 防重複綁定
link.dataset.enhanced = 'true';
link.addEventListener('click', function(e) {
// 1. 若為新分頁/下載/外部連結,不攔截
if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
if (this.target === '_blank' || this.download) return;
if (this.origin !== location.origin) return;
e.preventDefault();
// 2. 進入 Loading 狀態
const originalText = this.textContent;
this.textContent = 'Loading';
this.classList.add('loading');
this.setAttribute('aria-busy', 'true');
this.removeEventListener('click', arguments.callee); // 移除自身防重複
// 3. 動畫:每 150ms 加一個點,最多 3 點後循環
let dots = 0;
const animate = () => {
dots = (dots + 1) % 4;
this.textContent = 'Loading' + '.'.repeat(dots);
this.animationTimer = setTimeout(animate, 150);
};
animate();
// 4. 頁面跳轉(給動畫一點時間顯示)
setTimeout(() => {
window.location.href = this.href;
}, 100);
});
});
}
// 自動啟用
document.addEventListener('DOMContentLoaded', () => enhanceArticleLinks());
.entry-title a.loading {
position: relative;
color: transparent; /* 隱藏文字 */
}
.entry-title a.loading::after {
content: 'Loading';
position: absolute; left: 0; top: 0;
color: currentColor;
animation: loading-dots 1.2s steps(3) infinite;
}
@keyframes loading-dots {
0% { content: 'Loading'; }
33% { content: 'Loading.'; }
66% { content: 'Loading..'; }
100% { content: 'Loading...'; }
}
純 CSS 動畫:不佔用 JS 主執行緒、60fps 流暢、可被 `prefers-reduced-motion` 停用。
// 若使用 View Transitions API (Chrome 111+)
link.addEventListener('click', e => {
if (!document.startViewTransition) return; // 不支援則走原本邏輯
e.preventDefault();
document.startViewTransition(() => {
window.location.href = link.href;
});
});
// React Hook 版
function useLoadingLink() {
const [loading, setLoading] = useState(false);
const handleClick = (e) => {
if (e.metaKey || e.ctrlKey) return;
e.preventDefault();
setLoading(true);
setTimeout(() => window.location.href = e.currentTarget.href, 100);
};
return { loading, handleClick };
}
// 使用
function ArticleTitle({ href, children }) {
const { loading, handleClick } = useLoadingLink();
return
{loading ? 'Loading...' : children}
;
}
從簡單的 jQuery 片段演進到現代框架整合,核心精神不變:**給使用者即時、清晰、可預期的回饋**。