「回到頂部」是長頁面的標配功能。早期用 setTimeout 遞歸 + scrollTo 計算步長,現代瀏覽器推薦 requestAnimationFrame (rAF) 配合 scrollBehavior: 'smooth' 或自定義緩動函數,性能更好、動畫更絲滑。
/* CSS */
html { scroll-behavior: smooth; }
/* HTML */
/* JS 僅控制顯示/隱藏 */
const btn = document.getElementById('backTop');
window.addEventListener('scroll', () => {
btn.hidden = window.scrollY < 200;
});
btn.onclick = () => window.scrollTo({top: 0, behavior: 'smooth'});
/**
* 平滑滾動到頂部
* @param {number} duration 動畫時長 ms,默認 500
* @param {Function} easing 緩動函數 t∈[0,1] => 進度,默認 easeOutCubic
*/
function scrollToTop(duration = 500, easing = t => 1 - Math.pow(1 - t, 3)) {
const startY = window.scrollY || document.documentElement.scrollTop;
const startTime = performance.now();
function step(now) {
const elapsed = now - startTime;
const progress = Math.min(elapsed / duration, 1);
const eased = easing(progress);
window.scrollTo(0, startY * (1 - eased));
if (progress < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
// 使用
const btn = document.getElementById('backTop');
btn.onclick = () => scrollToTop(600); // 600ms 緩動
const easings = {
linear: t => t,
easeOutCubic: t => 1 - Math.pow(1 - t, 3),
easeOutQuart: t => 1 - Math.pow(1 - t, 4),
easeOutExpo: t => t === 1 ? 1 : 1 - Math.pow(2, -10 * t),
easeInOutQuad: t => t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2
};
// 原始碼邏輯修正版
function gotoTopLegacy(speed = 0.1, interval = 16) {
const x = document.documentElement.scrollLeft || document.body.scrollLeft;
const y = document.documentElement.scrollTop || document.body.scrollTop;
if (x === 0 && y === 0) return;
const nextX = Math.floor(x / (1 + speed));
const nextY = Math.floor(y / (1 + speed));
window.scrollTo(nextX, nextY);
setTimeout(() => gotoTopLegacy(speed + 0.02, interval), interval); // speed 遞增模擬緩動
}
⚠️ 此寫法**不推薦用於新項目**:定時器不精準、速度參數難控制、無法取消、移動端卡頓明顯。
<style>
#backTop {
position: fixed; right: 20px; bottom: 20px; z-index: 999;
width: 44px; height: 44px; border-radius: 50%;
background: rgba(0,0,0,.6); color: #fff; border: none;
cursor: pointer; opacity: 0; visibility: hidden; transform: translateY(20px);
transition: opacity .2s, visibility .2s, transform .2s;
}
#backTop.visible { opacity: 1; visibility: visible; transform: none; }
#backTop:focus { outline: 2px solid #fff; outline-offset: 2px; }
</style>
<button id="backTop" aria-label="回到頂部" title="回到頂部">↑</button>
<script>
(() => {
const btn = document.getElementById('backTop');
const THRESHOLD = 200;
let rafId = null;
// 滾動監聽:節流顯示/隱藏
const onScroll = () => {
btn.classList.toggle('visible', window.scrollY > THRESHOLD);
};
window.addEventListener('scroll', onScroll, {passive: true});
// 點擊平滑滾動
btn.addEventListener('click', () => {
if (rafId) cancelAnimationFrame(rafId);
const startY = window.scrollY;
const start = performance.now();
const duration = 500;
const ease = t => 1 - Math.pow(1 - t, 3);
function animate(now) {
const p = Math.min((now - start) / duration, 1);
window.scrollTo(0, startY * (1 - ease(p)));
if (p < 1) rafId = requestAnimationFrame(animate);
else rafId = null;
}
rafId = requestAnimationFrame(animate);
});
// 鍵盤支持:Home 鍵直達頂部
window.addEventListener('keydown', e => {
if (e.key === 'Home' && e.ctrlKey) {
e.preventDefault();
btn.click();
}
});
})();
</script>
| 方案 | 主線程佔用 | 動畫幀率 | 可取消 | 瀏覽器支持 |
|---|---|---|---|---|
| CSS scroll-behavior | 極低(瀏覽器內部) | 60fps | ❌ | 現代瀏覽器 |
| rAF + 緩動 | 低(每幀幾微秒) | 60fps | ✅ | IE10+ |
| setTimeout 遞歸 | 中(定時器堆積) | 不穩定 | ✅ | 全瀏覽器 |
html { scroll-behavior: smooth } + 顯隱按鈕 JS。requestAnimationFrame 封裝 scrollToTop()。setTimeout 版,但標記棄用,逐步遷移。aria-label、焦點樣式、鍵盤快捷鍵,滿足無障礙要求。