萬盛學電腦網

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

jQuery 滾動到頂部/底部動畫:animate(scrollTop) 兩行代碼實現

頁面內平滑滾動到頂部或底部是常見交互需求。本文提供基於 jQuery animate() 的極簡實現,解析scrollTop、offset().top座標體系,並給出原生 JS、CSS Scroll Behavior、IntersectionObserver 現代替代方案。

極簡 jQuery 實現 (原文核心)

<a href="#" id="goTop">回頂部</a>
<a href="#" id="goBottom">去底部</a>
<span id="bottomAnchor"></span> <!-- 底部錨點 -->

<script src="jquery-3.6.0.min.js"></script>
<script>
$(function() {
    // 回頂部:scrollTop 動畫到 0
    $('#goTop').click(function(e) {
        e.preventDefault();
        $('html, body').animate({ scrollTop: 0 }, 800); // 800ms
    });
    
    // 去底部:動畫到錨點 offset().top
    $('#goBottom').click(function(e) {
        e.preventDefault();
        $('html, body').animate({ 
            scrollTop: $('#bottomAnchor').offset().top 
        }, 800);
    });
});
</script>

關鍵點解析

  • $('html, body'):跨瀏覽器兼容,Chrome/FF 需html,Safari/舊IE 需body
  • scrollTop: 0:文檔滾動距離歸零
  • offset().top:目標元素相對**文檔**的垂直座標 (含邊距)
  • animate(..., duration):jQuery 內部用setInterval逐幀修改scrollTop
  • e.preventDefault():阻止href="#"默認跳轉行為

原生 JS 現代實現 (無依賴)

// 1. CSS Scroll Behavior (最簡單,無動畫控制)
document.documentElement.style.scrollBehavior = 'smooth';
document.getElementById('goTop').onclick = () => window.scrollTo({ top: 0, behavior: 'smooth' });
document.getElementById('goBottom').onclick = () => document.getElementById('bottomAnchor').scrollIntoView({ behavior: 'smooth' });

// 2. requestAnimationFrame 手寫動畫 (完全控制)
function smoothScrollTo(targetY, duration = 800) {
    const startY = window.scrollY;
    const diff = targetY - startY;
    const startTime = performance.now();
    
    function step(now) {
        const progress = Math.min((now - startTime) / duration, 1);
        const eased = 1 - Math.pow(1 - progress, 3); // easeOutCubic
        window.scrollTo(0, startY + diff * eased);
        if (progress < 1) requestAnimationFrame(step);
    }
    requestAnimationFrame(step);
}

// 使用
document.getElementById('goTop').onclick = () => smoothScrollTo(0);
document.getElementById('goBottom').onclick = () => smoothScrollTo(document.body.scrollHeight);

進階:顯示/隱藏「回頂部」按鈕

<style>
#goTop { position: fixed; right: 20px; bottom: 20px; display: none; z-index: 999; }
#goTop.visible { display: block; }
</style>

<script>
const goTop = document.getElementById('goTop');
window.addEventListener('scroll', () => {
    if (window.scrollY > 300) goTop.classList.add('visible');
    else goTop.classList.remove('visible');
}, { passive: true });

// 防抖優化 (可選)
const debounced = debounce(() => { /* 同上 */ }, 50);
window.addEventListener('scroll', debounced, { passive: true });

方案對比總結

方案代碼量控制力性能兼容性
jQuery animate極少中等中等 (主線程定時器)全瀏覽器 (需jQuery)
CSS scroll-behavior零JS低 (無暫停/回調)高 (瀏覽器原生)現代瀏覽器 (IE不支援)
scrollIntoView({behavior:'smooth'})極少低高現代瀏覽器
requestAnimationFrame 手寫中等完全 (緩動/暫停/回調)高 (對齊幀率)現代瀏覽器
GSAP ScrollToPlugin少專業級高需引入庫

無障礙建議

  • 按鈕添加aria-label="回到頂部"
  • 鍵盤可聚焦tabindex="0"
  • 尊重prefers-reduced-motion媒體查詢,關閉動畫
copyright © 萬盛學電腦網 all rights reserved