萬盛學電腦網

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

jQuery 錨點平滑滾動:從基礎到生產級的完整實作與無障礙加強

最精簡版(jQuery 3.x+)

$(document).on('click', 'a[href^="#"]', function(e) {
  const targetId = this.hash;
  if (!targetId) return;
  const $target = $(targetId);
  if (!$target.length) return;

  e.preventDefault();
  $('html, body').animate({ scrollTop: $target.offset().top }, 500, () => {
    $target.attr('tabindex', '-1').focus(); // 無障礙:焦點移至目標
    history.pushState(null, '', targetId);  // 更新 URL 不重載
  });
});

生產級完整版(原生 JS,零依賴,約 1.5 KB gzip)

class SmoothScroll {
  constructor(options = {}) {
    this.duration = options.duration || 800;
    this.easing = options.easing || 'easeInOutCubic';
    this.offset = options.offset || 0; // 固定導航欄高度
    this.updateURL = options.updateURL !== false;
    this._bind();
  }

  _bind() {
    document.addEventListener('click', e => {
      const anchor = e.target.closest('a[href^="#"]');
      if (!anchor) return;
      const hash = anchor.hash;
      if (!hash) return;
      const target = document.querySelector(hash);
      if (!target) return;
      e.preventDefault();
      this.scrollTo(target, hash);
    });
  }

  scrollTo(target, hash) {
    const start = window.scrollY;
    const targetTop = target.getBoundingClientRect().top + start - this.offset;
    const distance = targetTop - start;
    const startTime = performance.now();

    const ease = {
      linear: t => t,
      easeInOutCubic: t => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2,
      easeOutQuart: t => 1 - Math.pow(1 - t, 4)
    }[this.easing];

    const animate = now => {
      const elapsed = now - startTime;
      const progress = Math.min(elapsed / this.duration, 1);
      window.scrollTo(0, start + distance * ease(progress));
      if (progress < 1) requestAnimationFrame(animate);
      else this._finish(target, hash);
    };
    requestAnimationFrame(animate);
  }

  _finish(target, hash) {
    // 無障礙:焦點移至目標
    target.setAttribute('tabindex', '-1');
    target.focus({ preventScroll: true });
    // 更新 URL
    if (this.updateURL) history.pushState(null, '', hash);
  }
}

// 初始化
new SmoothScroll({
  duration: 800,
  easing: 'easeInOutCubic',
  offset: 72, // 固定 header 高度
  updateURL: true
});

CSS 滾動行為(現代瀏覽器零 JS 方案)

html {
  scroll-behavior: smooth; /* 基礎平滑滾動 */
}

/* 尊重用戶減少動畫偏好 */
@media (prefers-reduced-motion: reduce) {
  html { scroll-behavior: auto; }
}

/* 固定導航欄偏移(CSS Scroll Snap / scroll-padding) */
html { scroll-padding-top: 72px; } /* 等同 offset */
:target { scroll-margin-top: 72px; }

⚠️ `scroll-behavior: smooth` **無法**控制動畫時長、緩動函數、完成回調、焦點管理。複雜需求仍需 JS。

無障礙(a11y)檢查清單

項目實作
焦點管理滾動結束後 `target.focus({preventScroll:true})`,`tabindex="-1"` 使非互動元素可聚焦
語意化`` 保留原生錨點語意
鍵盤可用Tab 可達到錨點,Enter 觸發滾動
減少動畫檢測 `prefers-reduced-motion`,跳過動畫直接 `scrollTo`
URL 同步`history.pushState` 更新 hash,支援瀏覽器前進/後退、分享連結

進階場景處理

  • 動態內容/懶加載:目標元素尚未渲染 → `IntersectionObserver` 等待出現再滾動,或 `setTimeout` 輪詢。
  • 固定表頭表格:`scroll-padding-top` / `scroll-margin-top` 避免錨點被固定 header 遮擋。
  • SPA 路由整合:Vue Router / React Router `scrollBehavior` 選項原生支援平滑滾動。
  • 橫向滾動:`scrollLeft` + `getBoundingClientRect().left` 同理。

效能優化

  • 事件委託 `document.addEventListener('click', ...)` 而非每個錨點綁定。
  • `requestAnimationFrame` 替代 `setTimeout`,對齊螢幕重繪,零幀丟失。
  • 被動監聽器不適用(需 `preventDefault`),但點擊事件本身不影響滾動效能。

結語

錨點平滑滾動看似簡單,**無障礙焦點管理、固定導航偏移、減少動畫偏好、URL 同步、動態內容適配** 才是專業與業餘的分水嶺。現代專案優先用 CSS `scroll-behavior` + `scroll-padding` 覆蓋 80% 場景,複雜需求上輕量原生 JS Class,徹底拋棄 jQuery `animate` 依賴。

copyright © 萬盛學電腦網 all rights reserved