萬盛學電腦網

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

JavaScript 實現返回頂部懸浮按鈕:滾動監聽與平滑滾動

核心實現

<style>
.rTop { 
  width: 100px; height: 25px; line-height: 25px; text-align: center; 
  border: 1px solid #999; border-bottom-color: #333; border-right-color: #333;
  position: fixed; right: 0; bottom: 0; margin: 5px; cursor: pointer; display: none; 
}
</style>

<div class="rTop" id="rTop" onclick="toTop()">返回頂部</div>

<script>
// 滾動監聽:超過 0 顯示,否則隱藏
window.onscroll = function() {
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    document.getElementById('rTop').style.display = scrollTop > 0 ? 'block' : 'none';
};

// 點擊平滑返回頂部
function toTop() {
    window.scrollTo(0, 0); // 瞬間跳轉
    document.getElementById('rTop').style.display = 'none';
}
</script>

關鍵技術點

  1. 固定定位:position: fixed; right: 0; bottom: 0; 相對視口固定,不隨滾動移動。
  2. 滾動距離獲取:document.documentElement.scrollTop(標準模式)兼容 document.body.scrollTop(怪癖模式)。
  3. 顯示/隱藏切換:根據 scrollTop > 0 切換 display。
  4. scrollTo(0,0):瞬間回到頂部,無動畫。

進階:平滑滾動動畫

原生 CSS 滾動行為

html { scroll-behavior: smooth; } /* 一行搞定,現代瀏覽器支持 */

配合 window.scrollTo({top: 0, behavior: 'smooth'}) 可控制單次滾動行為。

JS 緩動動畫(兼容舊瀏覽器)

function smoothScrollToTop(duration = 500) {
    const start = window.scrollY;
    const startTime = performance.now();
    function step(now) {
        const progress = Math.min((now - startTime) / duration, 1);
        const ease = 1 - Math.pow(1 - progress, 3); // easeOutCubic
        window.scrollTo(0, start * (1 - ease));
        if (progress < 1) requestAnimationFrame(step);
        else document.getElementById('rTop').style.display = 'none';
    }
    requestAnimationFrame(step);
}

完善:節流滾動監聽

let ticking = false;
window.addEventListener('scroll', () => {
    if (!ticking) {
        requestAnimationFrame(() => {
            const scrollTop = window.scrollY || document.documentElement.scrollTop;
            document.getElementById('rTop').style.display = scrollTop > 100 ? 'block' : 'none';
            ticking = false;
        });
        ticking = true;
    }
}, {passive: true});

passive: true 告知瀏覽器不調用 preventDefault,優化滾動性能。

無障礙與 UX 細節

  • aria-label="返回頂部"、role="button"、tabindex="0" 支持鍵盤操作。
  • 添加 Enter/Space 鍵盤觸發。
  • 滾動超過一定距離(如 200px)再顯示,避免頂部閃爍。
  • 頁面底部留白,防止按鈕遮擋內容。
copyright © 萬盛學電腦網 all rights reserved