頁面內平滑滾動到頂部或底部是常見交互需求。本文提供基於 jQuery animate() 的極簡實現,解析scrollTop、offset().top座標體系,並給出原生 JS、CSS Scroll Behavior、IntersectionObserver 現代替代方案。
<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 需bodyscrollTop: 0:文檔滾動距離歸零offset().top:目標元素相對**文檔**的垂直座標 (含邊距)animate(..., duration):jQuery 內部用setInterval逐幀修改scrollTope.preventDefault():阻止href="#"默認跳轉行為// 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媒體查詢,關閉動畫