萬盛學電腦網

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

jQuery 平滑滾動至頂部/底部:無障礙回到頂部按鈕實作

「回到頂部」按鈕是長頁面的標準配備。本文提供一個無障礙、可配置、支援平滑滾動的完整實作,涵蓋 HTML 結構、CSS 樣式、jQuery 邏輯、鍵盤操作與進階擴充(滾動至底部、進度指示器)。

最小可行實作(3 行核心代碼)

<button id="backToTop" aria-label="回到頂部" hidden>↑</button>

<script>
$('#backToTop').on('click', () => $('html, body').animate({ scrollTop: 0 }, 400));
$(window).on('scroll', () => $('#backToTop').toggle($(window).scrollTop() > 200));
</script>

生產級完整版

HTML

<button 
  id="scrollControls" 
  class="scroll-btn scroll-top" 
  aria-label="回到頂部" 
  title="回到頂部"
  hidden
>
  <svg aria-hidden="true" viewBox="0 0 24 24"><path d="M7 14l5-5 5 5"/></svg>
</button>
<button 
  class="scroll-btn scroll-bottom" 
  aria-label="跳至底部" 
  title="跳至底部"
  hidden
>
  <svg aria-hidden="true" viewBox="0 0 24 24"><path d="M7 10l5 5 5-5"/></svg>
</button>

CSS(含動畫、響應式、無隱藏焦點)

.scroll-btn {
  position: fixed;
  right: 20px;
  width: 44px; height: 44px;
  border: none;
  border-radius: 50%;
  background: #2c3e50;
  color: #fff;
  opacity: 0.7;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0,0,0,.2);
  transition: opacity .2s, transform .2s, background .2s;
  z-index: 1000;
}
.scroll-btn:hover, .scroll-btn:focus {
  opacity: 1;
  transform: scale(1.1);
  outline: 3px solid #3498db;
  outline-offset: 2px;
}
.scroll-top { bottom: 80px; }
.scroll-bottom { bottom: 20px; }
.scroll-btn[hidden] { display: none; }

@media (max-width: 600px) {
  .scroll-btn { width: 40px; height: 40px; right: 12px; }
  .scroll-top { bottom: 70px; }
}

JavaScript (jQuery)

(function ($) {
  const $top = $('.scroll-top');
  const $bottom = $('.scroll-bottom');
  const SHOW_THRESHOLD = 200; // px
  const SCROLL_DURATION = 400; // ms

  // 顯示/隱藏邏輯
  function toggleVisibility() {
    const scrolled = $(window).scrollTop();
    const docHeight = $(document).height();
    const winHeight = $(window).height();
    
    $top.toggle(scrolled > SHOW_THRESHOLD);
    $bottom.toggle(scrolled + winHeight < docHeight - SHOW_THRESHOLD);
  }

  // 平滑滾動至頂部
  $top.on('click', function () {
    $('html, body').animate({ scrollTop: 0 }, SCROLL_DURATION, 'swing');
    $top.blur(); // 移除焦點避免殘留 outline
  });

  // 平滑滾動至底部
  $bottom.on('click', function () {
    const target = $(document).height() - $(window).height();
    $('html, body').animate({ scrollTop: target }, SCROLL_DURATION, 'swing');
    $bottom.blur();
  });

  // 鍵盤支援:Home/End 鍵
  $(document).on('keydown', function (e) {
    if (e.key === 'Home' && !$top.is('[hidden]')) { e.preventDefault(); $top.click(); }
    if (e.key === 'End' && !$bottom.is('[hidden]')) { e.preventDefault(); $bottom.click(); }
  });

  // 節流滾動監聽
  let ticking = false;
  $(window).on('scroll', function () {
    if (!ticking) {
      requestAnimationFrame(() => { toggleVisibility(); ticking = false; });
      ticking = true;
    }
  });

  // 初始檢查
  toggleVisibility();
})(jQuery);

進階擴充:滾動進度指示器

// 在按鈕外層加一個環狀進度條
const $ring = $('').insertAfter('.scroll-top');
$ring.css({
  position: 'fixed', right: '20px', bottom: '80px',
  width: '44px', height: '44px',
  border: '3px solid #ecf0f1', borderRadius: '50%',
  borderTopColor: '#3498db',
  animation: 'spin 1s linear infinite',
  display: 'none'
});

$(window).on('scroll', () => {
  const progress = $(window).scrollTop() / ($(document).height() - $(window).height());
  $ring.toggle(progress > 0 && progress < 1);
});

無障礙檢查清單

  • ✅ aria-label 提供語意
  • ✅ title 提供滑鼠懸停提示
  • ✅ 焦點可見(outline + outline-offset)
  • ✅ 鍵盤可操作
  • ✅ hidden 屬性控制顯示/隱藏(而非 display:none 切換)
  • ✅ SVG 圖示加 aria-hidden="true"
  • ✅ 色彩對比度符合 WCAG AA

結語

一個優秀的「回到頂部」功能不僅是 animate({scrollTop:0}),更包含顯示時機控制、平滑動畫、鍵盤支援、無障礙屬性、響應式設計。將上述程式碼封裝為 jQuery Plugin 或框架元件(Vue Directive / React Hook),即可在專案中一鍵複用,提升長頁面使用者體驗。

copyright © 萬盛學電腦網 all rights reserved