點擊「返回頂部」或頁內連結時,若能平滑捲動而非瞬間跳轉,使用體驗會好很多。本文示範如何用 jQuery 的 animate 實作平滑捲動到指定錨點的效果。
只要為目標元素設定 id,並讓連結的 href 指向該 id,就能透過下面的程式取得目標位置並以動畫捲動過去:
// HTML:
// <h1 id="anchor">Lorem Ipsum</h1>
// <p><a href="#anchor" class="topLink">Back to Top</a></p>
$(document).ready(function() {
$("a.topLink").click(function() {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
}, {
duration: 500,
easing: "swing"
});
return false;
});
});
關鍵在於用 $(this).attr("href") 取得目標選擇器,再用 .offset().top 算出該元素的垂直位置,最後 animate 到該 scrollTop。duration 控制時間、easing 控制加減速曲線,return false 則避免瀏覽器執行預設的瞬跳。無論是回到頁首或跳往頁尾,都能流暢呈現。