DIV CSS 佈局教程網

純文字版「返回頂部」的 JS 實作
編輯:JavaScript綜合知識     

這是一個不依賴任何函式庫、只用原生 JavaScript 的返回頂部寫法。它會自動判斷目前捲動位置是掛在 documentElement 還是 body 上,再以「每次移動剩餘距離的固定比例」做出先快後慢的平滑效果。

<script language="javascript">
var goto_top_type = -1;
var goto_top_itv = 0;

function goto_top_timer() {
  var y = goto_top_type == 1 ? document.documentElement.scrollTop : document.body.scrollTop;
  var moveby = 15;
  y -= Math.ceil(y * moveby / 100); // 每次移動剩餘距離的 15%
  if (y < 0) { y = 0; }
  if (goto_top_type == 1) { document.documentElement.scrollTop = y; }
  else { document.body.scrollTop = y; }
  if (y == 0) { clearInterval(goto_top_itv); goto_top_itv = 0; }
}

function goto_top() {
  if (goto_top_itv == 0) {
    if (document.documentElement && document.documentElement.scrollTop) { goto_top_type = 1; }
    else if (document.body && document.body.scrollTop) { goto_top_type = 2; }
    else { goto_top_type = 0; }
    if (goto_top_type > 0) { goto_top_itv = setInterval('goto_top_timer()', 50); }
  }
}
</script>

<a href="javascript:void(0)" onclick="goto_top()">【返回頂部】</a>

設計巧思在 y -= Math.ceil(y * moveby / 100):每次只移動「剩餘距離的 15%」,因此離頂部越遠滑得越快、越靠近頂部越慢,形成自然的緩動(ease-out)手感。每 50 毫秒觸發一次,直到 y 歸零才 clearInterval,並用 goto_top_itv 旗標避免重複啟動計時器。

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