點擊目錄要跳到對應章節、按下「回到頂端」要優雅地滑上去——這些都需要「平滑捲動」。以下先手寫一版理解原理,再說明現代標準做法。
// 計算元素相對於文件的絕對位置
function elementPosition(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
}
}
return { x: curleft, y: curtop };
}
// 平滑捲動到指定 id 的元素
function ScrollToControl(id) {
var elem = document.getElementById(id);
var scrollPos = elementPosition(elem).y;
// 扣掉目前已經捲掉的量,得到還需要移動的距離
scrollPos = scrollPos - document.documentElement.scrollTop;
var remainder = scrollPos % 50;
var repeatTimes = (scrollPos - remainder) / 50;
ScrollSmoothly(scrollPos, repeatTimes);
window.scrollBy(0, remainder);
}
var repeatCount = 0;
var cTimeout;
function ScrollSmoothly(scrollPos, repeatTimes) {
if (repeatCount < repeatTimes) {
window.scrollBy(0, 50); // 每次移動 50px
} else {
repeatCount = 0;
clearTimeout(cTimeout);
return;
}
repeatCount++;
cTimeout = setTimeout(
"ScrollSmoothly('" + scrollPos + "','" + repeatTimes + "')", 10
);
}
ScrollToControl('elementID');
呼叫後頁面就會平滑地捲到該元素所在的位置。
elementPosition() 透過不斷往上串 offsetParent,把每一層的偏移量累加起來,算出元素相對整個文件的絕對座標。這是手寫捲動動畫的基礎。
ScrollSmoothly() 則用最樸素的「分步累加」:每次捲 50px、間隔 10ms,重複足夠次數後停手。最後剩下的不足 50px 的部分,用一次 scrollBy 補完。
用字串呼叫 setTimeout 是不好的示範。字串形式等同偷偷執行 eval(),效能與安全性都吃虷,而且無法存取閉包變數。應改傳函式參照。
固定步長導致速度不均勻。長距離捲動會花很久、短距離又顯得突兀,而且起訖沒有加減速,看起來很機械。好的動畫需要 ease-in-out 之類的緩動曲線。
沒有處理連點的情況。使用者連續點兩次不同項目時,兩組計時器會互相打架。
只處理垂直方向。實際需求常包含水平捲動。
這個需求現在有標準 API,一行搞定,而且自帶系統級的順暢動畫:
// 基本用法
document.getElementById('target').scrollIntoView({ behavior: 'smooth' });
// 對齊方式可指定
document.getElementById('target').scrollIntoView({
behavior: 'smooth',
block: 'start', // 元素頂端對齊捲動容器頂端
inline: 'nearest'
});
若只想捲動視窗到某個位置:
window.scrollTo({ top: 500, behavior: 'smooth' });
要搭配固定高度的頁首時,記得用 CSS 的 scroll-margin-top 或 scroll-padding-top 預留空間,否則標題會被頁首蓋住。
<style>
html { scroll-behavior: smooth; } /* 全站預設平滑 */
section { scroll-margin-top: 80px; } /* 避開固定頁首 */
</style>
設了 scroll-behavior: smooth 之後,連純 CSS 的頁內錨點連結也會自動變成平滑捲動,完全不需要 JavaScript。