通過 setInterval 定時器逐步減小 scrollTop 值,配合 window.scrollTo() 實現平滑滾動效果。關鍵在於計算每幀的滾動距離,避免突兀跳轉。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>平滑返回頂部</title>
<style>
.content { height: 3000px; text-align: center; font-size: 50px; }
#backTop {
position: fixed; right: 20px; bottom: 30px;
width: 50px; height: 50px; line-height: 50px;
background: #333; color: #fff; border-radius: 50%;
cursor: pointer; text-align: center; font-size: 14px;
opacity: 0; transition: opacity 0.3s;
}
#backTop.show { opacity: 1; }
</style>
</head>
<body>
<div class="content">頁面內容區域(向下滾動顯示返回按鈕)</div>
<div id="backTop" onclick="scrollToTop()">↑</div>
<script>
const backTop = document.getElementById('backTop');
// 滾動監聽:顯示/隱藏按鈕
window.addEventListener('scroll', () => {
backTop.classList.toggle('show', window.scrollY > 200);
});
// 平滑滾動到頂部
function scrollToTop() {
const start = window.scrollY;
const duration = 500; // 毫秒
const startTime = performance.now();
function step(currentTime) {
const progress = Math.min((currentTime - startTime) / duration, 1);
// 緩動函數:easeOutQuart
const ease = 1 - Math.pow(1 - progress, 4);
window.scrollTo(0, start * (1 - ease));
if (progress < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
</script>
</body>
</html>
瀏覽器原生動畫幀 API,性能更優、不掉幀、節省資源。
線性滾動感覺生硬,引入 easeOutQuart 等緩動算法,符合人類視覺慣性預期。
使用 passive: true 或防抖處理 scroll 事件,避免頻繁觸發影響性能。
/* 僅需一行 CSS,瀏覽器原生支援平滑滾動 */
html { scroll-behavior: smooth; }
/* 錨點跳轉即可實現 */
<a href="#top">返回頂部</a>
⚠️ 兼容性:現代瀏覽器均支援,IE 需 Polyfill。