萬盛學電腦網

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

jQuery animate 實現頁面平滑滾動定位到指定元素

前言

單頁應用、錨點導航、回頂部、錯誤定位等場景需平滑滾動到指定位置。jQuery animate() 配合 scrollTop 可實現跨瀏覽器平滑滾動,本文提供完整封裝與現代原生替代方案。

核心實現

// 通用滾動函數
function scrollToElement($target, offset, duration) {
    offset = offset || 0;      // 額外偏移(如固定導航欄高度)
    duration = duration || 300; // 動畫時長 ms
    
    var targetTop = $target.offset().top + offset;
    
    // 關鍵:同時動畫 html 和 body,兼容不同瀏覽器滾動容器
    $('html, body').animate({
        scrollTop: targetTop
    }, duration, 'swing', function() {
        // 動畫完成回調
        $target.focus(); // 可選:聚焦目標元素(無障礙)
    });
}

// 使用
$('#nav a').click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href'); // "#section1"
    var $target = $(href);
    if ($target.length) {
        scrollToElement($target, -70); // 扣除固定導航欄 70px
    }
});

關鍵技術點

1. $('html, body') 雙選擇器

Chrome/FF 滾動容器是 document.documentElement (html),Safari/舊版 IE 是 body。同時動畫雙選擇器覆蓋所有情況。

2. offset().top 獲取絕對位置

$target.offset().top 返回元素相對文檔頂部距離,含邊距、邊框、滾動偏移。

3. 偏移量修正

// 固定頂部導航欄高度
var navHeight = $('#navbar').outerHeight();
scrollToElement($target, -navHeight); // 負偏移量向上預留空間

4. 取消正在進行的動畫

// 防止連續點擊導致動畫排隊
$('html, body').stop(true, true).animate({ scrollTop: targetTop }, 300);
// stop(clearQueue, jumpToEnd): 清空隊列、跳到最終狀態

現代原生替代:scrollIntoView + scrollTo

Element.scrollIntoView()(最簡單)

// 基礎用法
document.getElementById('section1').scrollIntoView({ behavior: 'smooth' });

// 精確控制對齊方式
element.scrollIntoView({ 
    behavior: 'smooth', 
    block: 'start',   // start/center/end/nearest
    inline: 'nearest' 
});

window.scrollTo()(程序化控制)

window.scrollTo({
    top: targetTop,
    left: 0,
    behavior: 'smooth'
});

// 獲取目標位置(原生)
var targetTop = element.getBoundingClientRect().top + window.pageYOffset;

進階封裝:支援選擇器、回調、取消、歷史管理

var SmoothScroll = {
    _animating: false,
    
    to: function(selector, options) {
        options = Object.assign({
            offset: 0,
            duration: 300,
            easing: 'swing',
            callback: null,
            updateHash: false // 是否更新 URL hash
        }, options);
        
        var $target = typeof selector === 'string' ? $(selector) : selector;
        if (!$target.length) return Promise.reject('Target not found');
        
        var targetTop = $target.offset().top + options.offset;
        var $scroll = $('html, body');
        
        // 取消當前動畫
        if (this._animating) $scroll.stop(true, true);
        this._animating = true;
        
        return new Promise(function(resolve) {
            $scroll.animate({ scrollTop: targetTop }, options.duration, options.easing, function() {
                SmoothScroll._animating = false;
                if (options.updateHash && selector.startsWith('#')) {
                    history.pushState(null, null, selector);
                }
                if (options.callback) options.callback($target);
                resolve($target);
            });
        });
    },
    
    cancel: function() {
        $('html, body').stop(true, false);
        this._animating = false;
    }
};

// 使用
SmoothScroll.to('#section1', { offset: -70, updateHash: true })
    .then(function($el) { console.log('滾動完成', $el.attr('id')); });

無障礙(Accessibility)注意事項

  1. 焦點管理:滾動後 $target.focus() 或設置 tabindex="-1" 並 focus,確保屏幕閱讀器跟隨。
  2. 鍵盤導航:Tab 鍵可達性、Enter/Space 觸發滾動。
  3. 動畫減弱:尊重 @media (prefers-reduced-motion: reduce),關閉動畫 behavior: 'auto'。

總結

jQuery animate({scrollTop}) 是經典跨瀏覽器方案,核心要點:雙選擇器 html/body、offset().top 絕對位置、偏移修正、stop 防排隊。現代項目優先使用原生 scrollIntoView({behavior:'smooth'}),零依賴、性能更好、原生支援無障礙。複雜場景(偏移量、回調、歷史管理)可封裝 Promise 化工具函數。

copyright © 萬盛學電腦網 all rights reserved