點擊頁內錨點連結時,若能平滑地捲動到目標位置,而非瞬間跳轉,整體體驗會柔和許多。這用 jQuery 的 animate() 改變 scrollTop 就能實現。
以下程式碼攔截所有指向 # 的連結,判斷是否為同頁錨點後,計算目標元素的偏移量並平滑捲動:
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target
|| $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top;
var obj = document.documentElement;
if (jQuery.browser.safari) obj = document.body;
if (jQuery.browser.msie) obj = 'html';
$(obj).animate({ scrollTop: targetOffset }, 1000);
return false;
}
}
});
重點在於用 $target.offset().top 取得目標距頁首的距離,再 animate 到該 scrollTop。程式中針對 Safari 與 IE 分別指定捲動的目標元素,是為了相容不同瀏覽器的實作差異;而在現代瀏覽器中,直接對 $('html, body') 做 animate 通常就能順利運作。