萬盛學電腦網

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

純文字版「回到頂部」平滑滾動實作 (無依賴)

完整程式碼

<script>
var scrollType = -1, timer = 0;

function scrollStep() {
  var top = (scrollType === 1) ? document.documentElement.scrollTop : document.body.scrollTop;
  var move = Math.ceil(top * 0.15); // 15% 緩動
  top -= move;
  if (top < 0) top = 0;
  if (scrollType === 1) document.documentElement.scrollTop = top;
  else document.body.scrollTop = top;
  if (top === 0) { clearInterval(timer); timer = 0; }
}

function gotoTop() {
  if (timer) return;
  if (document.documentElement && document.documentElement.scrollTop) scrollType = 1;
  else if (document.body && document.body.scrollTop) scrollType = 2;
  else return;
  timer = setInterval(scrollStep, 50);
}
</script>
<a href="javascript:void(0)" onclick="gotoTop()">【回到頂部】</a>

原理解析

  1. 偵測 `document.documentElement.scrollTop` (標準模式) 或 `document.body.scrollTop` (相容模式)
  2. 每 50ms 執行一次,每次移動剩餘距離 15% (緩動效果)
  3. 到達 0 清除 timer

現代簡潔寫法 (CSS + 原生 API)

<style>html { scroll-behavior: smooth; }</style>
<a href="#top">回到頂部</a>
<!-- 或 -->
<button onclick="scrollTo({top:0,behavior:'smooth'})">回到頂部</button>

現代瀏覽器僅需一行 CSS 或 `scrollTo({behavior:'smooth'})`,無需 JS 計時器。

copyright © 萬盛學電腦網 all rights reserved