DIV CSS 佈局教程網

用原生 JS 實作減速滑動的回到頂部效果
編輯:關於JavaScript     

幾乎每個長頁面都會放一個「返回頂部」按鈕,尤其底部沒有導航的頁面更是必要。與其讓它瞬間跳回,做成滑動滾上去的過渡,體感會好很多;再進一步做成「越接近頂部速度越慢」的減速效果,就更貼近物理直覺了。

基本原理

做法是一個遞迴:讀取目前捲動距離 → 往上移動一段 → 再讀取一次 → 再往上移動一段(這次幅度更小)→ 直到距離歸零。每次移動的幅度是「目前距離 ÷ 速度」,而速度大於 1,於是幅度會自然遞減。

<script type="text/javascript">
/**
 * 回到頁面頂部
 * @param acceleration 加速度
 * @param time 時間間隔(毫秒)
 */
function goTop(acceleration, time) {
  acceleration = acceleration || 0.1;
  time = time || 16;

  var x1 = 0, y1 = 0, x2 = 0, y2 = 0, x3 = 0, y3 = 0;

  if (document.documentElement) {
    x1 = document.documentElement.scrollLeft || 0;
    y1 = document.documentElement.scrollTop || 0;
  }
  if (document.body) {
    x2 = document.body.scrollLeft || 0;
    y2 = document.body.scrollTop || 0;
  }
  x3 = window.scrollX || 0;
  y3 = window.scrollY || 0;

  // 取最大值以相容各家瀏覽器
  var x = Math.max(x1, Math.max(x2, x3));
  var y = Math.max(y1, Math.max(y2, y3));

  // 速度大於 1,因此每次移動的距離遞減
  var speed = 1 + acceleration;
  window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));

  if (x > 0 || y > 0) {
    var invokeFunction = "goTop(" + acceleration + ", " + time + ")";
    window.setTimeout(invokeFunction, time);
  }
}
</script>

呼叫方式:

<a href="#" onclick="goTop();return false;">TOP</a>

幾個細節說明

document.documentElement.scrollTop、document.body.scrollTop 與 window.scrollY 三者理論上數值相同,但實際上只有部分能在特定瀏覽器(尤其舊 IE 的 quirks mode)中取到正確值,因此用 Math.max 一次比完是最省事的相容寫法。

time 預設 16 毫秒,約等於 60fps 的一幀間隔,這個數值不是隨便挑的。

另外,setTimeout 傳字串("goTop(...)")會經過一次 eval,既慢又不安全。改成傳函式參照更好:

window.setTimeout(function(){
  goTop(acceleration, time);
}, time);

現代寫法

今天不必自己刻遞迴了,原生就有平滑捲動:

// 全域平滑回到頂部
window.scrollTo({ top: 0, behavior: 'smooth' });

// 指定元素的平滑捲動
document.querySelector('#target').scrollIntoView({ behavior: 'smooth' });

瀏覽器會自動處理加速曲線與 drop frames 的補償,效果比手刻的更順。若需要自訂曲線或時長,才需要回到 requestAnimationFrame 自行計算——但記得用 rAF 取代 setTimeout,讓動畫與螢幕刷新同步。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved