萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

為文章標題連結添加動態 Loading 效果:jQuery 實作與現代化改良

點擊文章標題時顯示「Loading...」動畫,能給使用者即時回饋,緩解等待焦慮。本文從原始 jQuery 實作出發,重構為現代、無障礙、效能優化的版本。

原始需求分析

  • 點擊標題連結 → 顯示「Loading...」動態文字 → 頁面跳轉
  • 防止重複點擊
  • 動畫為「Loading.」→「Loading..」→「Loading...」循環

現代化重構版(ES6 + 無障礙)

// 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());

CSS 動畫替代 JS 計時器(效能更好)

.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 / Vue 元件化範例

// 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 片段演進到現代框架整合,核心精神不變:**給使用者即時、清晰、可預期的回饋**。

copyright © 萬盛學電腦網 all rights reserved