$(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 不重載
});
});
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
});
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。
| 項目 | 實作 |
|---|---|
| 焦點管理 | 滾動結束後 `target.focus({preventScroll:true})`,`tabindex="-1"` 使非互動元素可聚焦 |
| 語意化 | `` 保留原生錨點語意 |
| 鍵盤可用 | Tab 可達到錨點,Enter 觸發滾動 |
| 減少動畫 | 檢測 `prefers-reduced-motion`,跳過動畫直接 `scrollTo` |
| URL 同步 | `history.pushState` 更新 hash,支援瀏覽器前進/後退、分享連結 |
錨點平滑滾動看似簡單,**無障礙焦點管理、固定導航偏移、減少動畫偏好、URL 同步、動態內容適配** 才是專業與業餘的分水嶺。現代專案優先用 CSS `scroll-behavior` + `scroll-padding` 覆蓋 80% 場景,複雜需求上輕量原生 JS Class,徹底拋棄 jQuery `animate` 依賴。