長頁面錨點跳轉預設為瞬間跳轉,用戶易迷失方向。本文示範使用 jQuery 實現「平滑滾動」錨點導航,支援垂直/水平滾動、自訂動畫時間、動態綁定,提升用戶體驗。
$.fn.anchorGoWhere = function(options) {
const $elements = this;
const opts = $.extend({
target: 1, // 1=垂直滾動, 2=水平滾動
timer: 500 // 動畫毫秒數
}, options);
$elements.each(function() {
const $el = $(this);
$el.on('click', function(e) {
e.preventDefault();
const href = $(this).attr('href');
if (!href || href === '#') return;
const targetId = href.startsWith('#') ? href.substring(1) : href;
const $target = $('#' + targetId);
if (!$target.length) return;
let scrollProp, targetPos;
if (opts.target === 1) { // 垂直
scrollProp = 'scrollTop';
targetPos = $target.offset().top;
} else { // 水平
scrollProp = 'scrollLeft';
targetPos = $target.offset().left;
}
$('html, body').animate({ [scrollProp]: targetPos }, opts.timer);
});
});
return this; // 支援鏈式調用
};
<nav>
<a href="#section1" id="btn1">去 Section 1</a>
<a href="#section2" id="btn2">去 Section 2</a>
<a href="#section3" id="btn3">去 Section 3</a>
</nav>
<section id="section1" style="height:800px;">內容 1</section>
<section id="section2" style="height:800px;">內容 2</section>
<section id="section3" style="height:800px;">內容 3</section>
$(function() {
// 綁定多個按鈕,統一配置
$('#btn1, #btn2, #btn3').anchorGoWhere({ target: 1, timer: 800 });
// 或單獨綁定不同配置
// $('#btnHorizontal').anchorGoWhere({ target: 2, timer: 1000 });
});
$elements.on('click', function(e) {
// ... 動畫邏輯 ...
// 動畫完成後更新 hash (不觸發跳轉)
$('html, body').animate({ [scrollProp]: targetPos }, opts.timer, function() {
history.pushState(null, null, '#' + targetId);
});
});
const headerHeight = $('#header').outerHeight();
targetPos = $target.offset().top - headerHeight;
$(window).on('scroll', function() {
const scrollPos = $(window).scrollTop() + headerHeight + 50; // 偏移量
$('section').each(function() {
const $sec = $(this);
if ($sec.offset().top <= scrollPos && $sec.offset().top + $sec.outerHeight() > scrollPos) {
$('.nav a').removeClass('active');
$('.nav a[href="#' + $sec.attr('id') + '"]').addClass('active');
}
});
});
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
const targetId = this.getAttribute('href').substring(1);
const target = document.getElementById(targetId);
if (target) {
target.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.pushState(null, null, '#' + targetId);
}
});
});
| 問題 | 原因 | 解決 |
|---|---|---|
| 滾動後立即跳回 | 未 e.preventDefault() 取消預設錨點跳轉 | 事件處理開頭加上 |
| 動畫卡頓 | 同時綁定多個 animate 於 html, body | 用 $('html, body').stop().animate(...) 清除佇列 |
| 目標元素找不到 | ID 重複、大小寫不符、元素未渲染 | 確保 ID 唯一、DOM 就緒後綁定 |
平滑滾動錨點導航是提升長頁面體驗的低成本高回報優化。本文提供的 anchorGoWhere 插件封裝了核心邏輯,支援垂直/水平、自訂時長、鏈式調用。現代專案可考慮原生 scrollIntoView({behavior:'smooth'}) 移除 jQuery 依賴,但需注意 Safari 舊版本相容性。