萬盛學電腦網

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

返回頂部按鈕完整實作:顯示邏輯、平滑滾動、動畫小飛豬與無障礙加強

核心需求拆解

  1. 顯示時機:頁面滾動超過閾值(如 300px)顯示,否則隱藏。
  2. 點擊行為:平滑滾動至頂部(`scrollTo({ top: 0, behavior: 'smooth' })`)。
  3. 進階花樣:飛豬/火箭發射動畫、滾動進度環、長按快速滾動。
  4. 無障礙:鍵盤可聚焦、語意化標籤、ARIA 標籤、減少動畫偏好。

現代極簡版(原生 API,無依賴)

<button id="backToTop" class="back-to-top" aria-label="返回頂部" hidden>
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <path d="M18 15l-6-6-6 6"/>
  </svg>
</button>

<style>
.back-to-top {
  position: fixed; right: 24px; bottom: 24px; z-index: 999;
  width: 48px; height: 48px; border-radius: 50%;
  background: #1976d2; color: #fff; border: none; cursor: pointer;
  box-shadow: 0 4px 12px rgba(0,0,0,.15);
  display: flex; align-items: center; justify-content: center;
  opacity: 0; transform: translateY(20px); transition: opacity .2s, transform .2s;
}
.back-to-top:not([hidden]) { opacity: 1; transform: translateY(0); }
.back-to-top:hover { background: #1565c0; }
.back-to-top:focus-visible { outline: 3px solid #90caf9; outline-offset: 3px; }
@media (prefers-reduced-motion: reduce) {
  .back-to-top { transition: none; }
  html { scroll-behavior: auto; }
}
</style>

<script>
const btn = document.getElementById('backToTop');
const SHOW_THRESHOLD = 300;

window.addEventListener('scroll', () => {
  btn.hidden = window.scrollY < SHOW_THRESHOLD;
}, { passive: true });

btn.addEventListener('click', () => {
  window.scrollTo({ top: 0, behavior: 'smooth' });
});
</script>

進階版:飛豬發射動畫 + 滾動進度環

<button id="backToTop" class="rocket" aria-label="返回頂部" hidden>
  <svg class="rocket__svg" viewBox="0 0 48 48">
    <circle class="rocket__track" cx="24" cy="24" r="20" fill="none" stroke="#eee" stroke-width="4"/>
    <circle class="rocket__progress" cx="24" cy="24" r="20" fill="none" stroke="#ffd600" stroke-width="4"
      stroke-linecap="round" stroke-dasharray="125.6" stroke-dashoffset="125.6" transform="rotate(-90 24 24)"/>
    <path class="rocket__icon" d="M24 8 L32 24 L16 24 Z" fill="#fff"/>
    <path class="rocket__fire" d="M20 30 L24 40 L28 30 Z" fill="#ff6d00" opacity="0"/>
  </svg>
</button>

<style>
.rocket { position:fixed; right:24px; bottom:24px; width:56px; height:56px; border:none; background:none; cursor:pointer; z-index:999; }
.rocket__track { transition: stroke-dashoffset .1s linear; }
.rocket__fire { transform-origin: 24px 30px; animation: fire .15s ease-in-out infinite alternate; }
@keyframes fire { from { transform: scaleY(1); } to { transform: scaleY(1.3); } }
.rocket.launch .rocket__icon { animation: launch .6s cubic-bezier(.5,0,.5,1) forwards; }
.rocket.launch .rocket__fire { opacity: 1; }
@keyframes launch { to { transform: translateY(-200vh) rotate(-15deg); opacity: 0; } }
</style>

<script>
const btn = document.getElementById('backToTop');
const progress = btn.querySelector('.rocket__progress');
const CIRCUMFERENCE = 2 * Math.PI * 20; // 125.6

window.addEventListener('scroll', () => {
  const scrollTop = window.scrollY;
  const docHeight = document.documentElement.scrollHeight - window.innerHeight;
  const progressRatio = Math.min(scrollTop / docHeight, 1);
  progress.style.strokeDashoffset = CIRCUMFERENCE * (1 - progressRatio);
  btn.hidden = scrollTop < 300;
}, { passive: true });

btn.addEventListener('click', () => {
  btn.classList.add('launch');
  window.scrollTo({ top: 0, behavior: 'smooth' });
  btn.addEventListener('animationend', () => btn.classList.remove('launch'), { once: true });
});
</script>

無障礙(a11y)強化清單

效能優化

  • 滾動監聽掛載 `{ passive: true }`,瀏覽器可並行處理滾動。
  • 使用 `IntersectionObserver` 監測頁尾元素顯示/隱藏按鈕,完全避免 `scroll` 事件(更省電)。
  • SVG 內聯避免額外請求,壓縮後 < 1 KB。

IntersectionObserver 替代方案

const sentinel = document.createElement('div');
sentinel.style.cssText = 'height:1px; margin-top:-1px;'; // 放在頁面底部
document.body.appendChild(sentinel);

const observer = new IntersectionObserver(([e]) => {
  btn.hidden = e.isIntersecting; // 頁尾可見 → 隱藏按鈕
}, { rootMargin: '300px' }); // 提前 300px 觸發
observer.observe(sentinel);

結語

返回頂部按鈕雖小,卻是「滾動體驗」的關鍵細節。現代瀏覽器原生 `scrollTo({behavior:'smooth'})` + `IntersectionObserver` + SVG 動畫,即可構建零依賴、高效能、無障礙、且具備品牌識別度的完美體驗。別再用 `setTimeout` 手動計算座標了——那是 10 年前的寫法。

copyright © 萬盛學電腦網 all rights reserved