萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 平滑回到頂部:requestAnimationFrame 現代實現

「回到頂部」是長頁面的標配功能。早期用 setTimeout 遞歸 + scrollTo 計算步長,現代瀏覽器推薦 requestAnimationFrame (rAF) 配合 scrollBehavior: 'smooth' 或自定義緩動函數,性能更好、動畫更絲滑。

方案一:原生 CSS 滾動(零 JS,最推薦)

/* 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'});
  • ✅ 無 JS 計算,瀏覽器原生優化,主線程零負擔
  • ✅ 支持鍵盤無障礙、減少動畫偏好
  • ⚠️ Safari < 15.4 不支持,需 Polyfill 或降級 JS

方案二:requestAnimationFrame + 緩動函數(全瀏覽器兼容)

/**
 * 平滑滾動到頂部
 * @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
};

方案三:舊版 setTimeout 遞歸(僅維護 IE9- 時使用)

// 原始碼邏輯修正版
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 遞增模擬緩動
}

⚠️ 此寫法**不推薦用於新項目**:定時器不精準、速度參數難控制、無法取消、移動端卡頓明顯。

完整組件化示例(含顯示/隱藏、無障礙、rAF)

<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 遞歸中(定時器堆積)不穩定✅全瀏覽器

總結建議

  1. 新項目:優先 html { scroll-behavior: smooth } + 顯隱按鈕 JS。
  2. 需精確控制/取消/自定義緩動:用 requestAnimationFrame 封裝 scrollToTop()。
  3. 維護 IE9- 專案:保留 setTimeout 版,但標記棄用,逐步遷移。
  4. 始終添加 aria-label、焦點樣式、鍵盤快捷鍵,滿足無障礙要求。
copyright © 萬盛學電腦網 all rights reserved