單頁應用、錨點導航、回頂部、錯誤定位等場景需平滑滾動到指定位置。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
}
});
Chrome/FF 滾動容器是 document.documentElement (html),Safari/舊版 IE 是 body。同時動畫雙選擇器覆蓋所有情況。
$target.offset().top 返回元素相對文檔頂部距離,含邊距、邊框、滾動偏移。
// 固定頂部導航欄高度
var navHeight = $('#navbar').outerHeight();
scrollToElement($target, -navHeight); // 負偏移量向上預留空間
// 防止連續點擊導致動畫排隊
$('html, body').stop(true, true).animate({ scrollTop: targetTop }, 300);
// stop(clearQueue, jumpToEnd): 清空隊列、跳到最終狀態
// 基礎用法
document.getElementById('section1').scrollIntoView({ behavior: 'smooth' });
// 精確控制對齊方式
element.scrollIntoView({
behavior: 'smooth',
block: 'start', // start/center/end/nearest
inline: 'nearest'
});
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')); });
$target.focus() 或設置 tabindex="-1" 並 focus,確保屏幕閱讀器跟隨。Tab 鍵可達性、Enter/Space 觸發滾動。@media (prefers-reduced-motion: reduce),關閉動畫 behavior: 'auto'。jQuery animate({scrollTop}) 是經典跨瀏覽器方案,核心要點:雙選擇器 html/body、offset().top 絕對位置、偏移修正、stop 防排隊。現代項目優先使用原生 scrollIntoView({behavior:'smooth'}),零依賴、性能更好、原生支援無障礙。複雜場景(偏移量、回調、歷史管理)可封裝 Promise 化工具函數。