點了「回到頂端」卻瞬間跳上去,體驗總是差了那麼一點。用 animate 動畫化 scrollTop,就能做出平滑捲動的效果。
// 捲動到 #qa 元素的位置
scrollOffset($("#qa").offset());
function scrollOffset(scroll_offset) {
$("body,html").animate({
scrollTop: scroll_offset.top - 70
}, 0);
}
$("#qa").offset() 取得元素相對於文件的座標(含捲動量),回傳 { top: …, left: … }。這與 position()(相對 offsetParent)不同,做頁面捲動時要的是 offset。
$("body,html").animate({ scrollTop: … }) 讓 jQuery 逐帧改寫捲動位置,產生平滑移動。選擇器同時寫 body 與 html,是為了相容不同瀏覽器——有的把捲動容器放在 body,有的放在 html 元素上,兩個都選就不必偵測。
那個 - 70 是偏移補償:若頁面有固定高度的頁首(fixed header),捲到元素正上方會被頁首遮住。減去頁首高度,目標才會露出來。這個數字應該對應你的頁首實際高度,而不是硬寫。
原範例把 duration 寫成 0,那等於沒有動畫——瞬間跳到底。要平滑效果請給實際毫秒數:
$("html, body").animate({ scrollTop: target }, 500, "swing");
用位置或 id 當目標。除了傳座標物件,也可以直接傳數字($(...).animate({scrollTop: 800})),或用 jQuery 內建的 $('html,body').scrollTop(target) 搭配 CSS scroll-behavior: smooth。
加上 .stop() 避免動畫堆積。使用者連續點擊時,動畫會排隊,畫面出現來回拉扯。前面加 .stop() 讓新動畫立即接手。
更新網址的 hash 更好用。捲動完成後把 hash 寫進網址(history.pushState),使用者就能分享連結、按上一頁回到原位置。
/* CSS 一行解決 */
html { scroll-behavior: smooth; }
/* 尊重使用者的動態效果偏好 */
@media (prefers-reduced-motion: reduce) {
html { scroll-behavior: auto; }
}
/* 讓固定頁首不遮住目標 */
#qa { scroll-margin-top: 70px; }
scroll-behavior: smooth 讓所有頁內跳轉(包含 <a href="#qa">)自動平滑捲動,完全不需要 JavaScript。scroll-margin-top 則取代了那個手寫的 -70,語意清楚且不必算數字。若需要「捲動完成後執行動作」,才用 element.scrollIntoView({ behavior: 'smooth' }) 搭配 scrollend 事件。