萬盛學電腦網

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

jQuery 實現平滑滾動至頁面頂部/錨點完整教學

前言

「回到頂部」按鈕與錨點平滑滾動是現代網站提升使用者體驗的標準配備。本文詳細解析如何使用 jQuery 實現平滑滾動,涵蓋基本實作、進階參數控制、以及常見坑點解決方案。

核心實作原理

利用 jQuery 的 .animate() 方法,將 scrollTop 屬性動畫過渡到目標位置。關鍵在於正確計算目標元素的文檔偏移量。

基礎版:回到頁面頂部

// HTML
<a href="#" class="back-to-top">回到頂部</a>

// jQuery
$('.back-to-top').on('click', function(e) {
    e.preventDefault(); // 阻止預設跳轉行為
    
    $('html, body').animate({
        scrollTop: 0 // 滾動到文檔頂部
    }, 500); // 500ms 動畫時長
});

進階版:滾動至任意錨點

// HTML 結構
<nav>
    <a href="#section1" class="scroll-link">第一章</a>
    <a href="#section2" class="scroll-link">第二章</a>
</nav>

<section id="section1">...</section>
<section id="section2">...</section>

// jQuery 通用處理器
$('.scroll-link').on('click', function(e) {
    e.preventDefault();
    
    const targetId = this.getAttribute('href'); // 取得 #section1
    const $target = $(targetId);
    
    if ($target.length) {
        $('html, body').animate({
            scrollTop: $target.offset().top // 目標元素距離文檔頂部的距離
        }, {
            duration: 800,
            easing: 'swing', // 或 'linear'
            complete: function() {
                // 動畫完成後可選:更新 URL hash 不觸發跳轉
                window.history.pushState(null, null, targetId);
            }
        });
    }
});

關鍵技術細節解析

為什麼要同時選取 `html, body`?

瀏覽器對滾動容器的處理不一致:

  • Chrome/Safari:document.body 是滾動容器
  • Firefox/IE/Edge:document.documentElement (<html>) 是滾動容器
  • 同時選取兩者可確保跨瀏覽器相容

動畫參數深度解析

$('html, body').animate({
    scrollTop: targetOffset
}, {
    duration: 600,        // 動畫時長(毫秒) 或 'fast'/'slow'
    easing: 'swing',      // 緩動函數:'swing'(預設) 或 'linear'
    queue: false,         // 不進入動畫佇列,避免連點堆疊
    complete: function() { /* 完成回呼 */ },
    step: function(now, fx) { /* 每幀回呼,可做進度條等 */ }
});

處理固定版頭偏移

若頁面有固定導航列 (position: fixed),滾動後內容會被遮擋,需扣除導航列高度:

const headerHeight = $('#fixed-header').outerHeight();
const targetTop = $target.offset().top - headerHeight - 20; // 額外留 20px 間距

$('html, body').animate({ scrollTop: targetTop }, 500);

現代化替代方案:原生 CSS Scroll Behavior

現代瀏覽器 (Chrome 61+, Firefox 36+, Safari 15+) 支援純 CSS 實現,無需 JavaScript:

/* CSS */
html {
    scroll-behavior: smooth;
}

/* HTML - 直接使用錨點連結即可 */
<a href="#section1">平滑滾動到第一章</a>

優點:零 JS 依賴、效能最佳、語意化。
缺點:無法控制動畫速度/緩動、無回呼函數、舊版瀏覽器不支援。

常見問題與解決方案

問題原因解決方案
動畫不執行/閃一下就停止 事件冒泡觸發多次、或 preventDefault 遺漏 確實呼叫 e.preventDefault(),檢查選擇器正確性
滾動位置不準確 目標元素邊距合併、或固定版頭遮擋 使用 offset().top 而非 position().top,扣除版頭高度
連點導致動畫排隊 預設進入 jQuery 動畫佇列 加上 queue: false 或使用 .stop(true) 清除佇列
移動端觸控衝突 觸控滾動與動畫競爭 偵測觸控裝置時降級為原生跳轉,或使用 touch-action CSS

完整生產級程式碼範本

;(function($) {
    $.fn.smoothScroll = function(options) {
        const settings = $.extend({
            duration: 600,
            easing: 'swing',
            offset: 0,
            callback: null,
            updateURL: true
        }, options);

        return this.on('click', function(e) {
            const href = this.getAttribute('href');
            if (!href || href === '#') return;
            
            const $target = $(href);
            if (!$target.length) return;
            
            e.preventDefault();
            
            const targetTop = $target.offset().top + settings.offset;
            
            $('html, body').stop(true).animate({
                scrollTop: targetTop
            }, {
                duration: settings.duration,
                easing: settings.easing,
                queue: false,
                complete: function() {
                    if (settings.updateURL) {
                        window.history.pushState(null, null, href);
                    }
                    if ($.isFunction(settings.callback)) {
                        settings.callback.call($target[0]);
                    }
                }
            });
        });
    };
})(jQuery);

// 使用方式
$('.scroll-link').smoothScroll({
    offset: -80, // 扣除 80px 固定版頭
    duration: 700,
    callback: function() { console.log('滾動完成:', this.id); }
});

總結

jQuery 平滑滾動雖然有原生 CSS 替代方案,但在需要精確控制動畫參數、回呼處理、或支援舊版瀏覽器的專案中仍具不可替代性。掌握 offset().top 計算、html, body 雙選取器、以及動畫佇列控制,是前端工程師的基本功。

copyright © 萬盛學電腦網 all rights reserved