點擊頁內錨點時,瀏覽器預設是直接跳過去,畫面硬邦邦地切換。加上一段平滑滾動,不僅視覺上舒服,也能讓使用者對「自己移動了多遠」有具體感受。核心程式碼只有十幾行:
$('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;
$('html,body').animate({ scrollTop: targetOffset }, 500);
return false;
}
}
});
幾個細節值得說明:
路徑與網域比對是為了避開外部連結。若 href 指向別的網站,就沒有滾動的意義,直接讓瀏覽器處理即可。
目標的尋找有兩段:先用 hash 當作 id 選擇器;找不到時,再退回去找同名元素,也就是舊式的 <a name="..."> 錨點。這讓新舊寫法都能相容。
return false 同時做了兩件事:阻止預設跳轉,也停止事件冒泡。如果你希望保留冒泡行為,可以改用 e.preventDefault()。
animate 的第二個參數 500 是毫秒,也就是 0.5 秒完成滾動,可依頁面長度自行調整。若想加上緩動效果,記得先引入 easing 外掛並指定第三個參數。