點擊錨點時,瀏覽器預設會「啪」地跳到目標位置。若改成平滑捲動過去,整體質感立刻不同。用 jQuery 只要幾行。
先在觸發處放一個連結:<a id="turnToContent" href="#content"></a>,並在目標位置放一個 <div id="content">。若頁面不夠長、效果不明顯,暫時在前面塞幾個 <br> 測試即可。
接著:
$('#turnToContent').click(function () {
$('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 500);
return false;
});
三個重點:$.attr(this, 'href') 取出 href 屬性值(也就是 "#content")並將它當成選擇器使用;offset().top 取得目標元素距頁面的絕對位置;return false 阻止瀏覽器執行預設的跳轉,否則會先跳再滑。
動畫的目標同時包含 html 與 body,是為了相容不同瀏覽器——捲動捲軸的到底是哪個元素,各家實作並不一致。
$('a[href*=#],area[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) {
$('html,body').animate({ scrollTop: $target.offset().top }, 1000);
return false;
}
}
});
這個版本的好處是幾乎不必修改就能用於全站所有錨點。它額外做了幾件事:比對 pathname 與 hostname,確認連結指向的是同一頁、同一網域,避免誤攔外部連結;先試 id 再試 name,相容舊式 <a name="..."> 錨點;用 $target.length 確認目標存在,找不到就讓瀏覽器走預設行為,不會報錯。同時也不干擾網址列的錨點,分享出去的連結仍然可用。
若目標區塊上方有固定定位的頁首,捲到 offset().top 會被遮住,應該再減去頁首高度。另外,長距離捲動時建議加上 prefers-reduced-motion 判斷,對偏好減少動態效果的使用者直接跳轉。最後,新專案其實一行 CSS 就能取代全部 JS:html { scroll-behavior: smooth; }——不需要 jQuery,也不會有 JS 失效就失效的風險。