萬盛學電腦網

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

JavaScript 實現平滑返回頂部按鈕:緩動動畫、滾動源判斷、定時器管理

核心實現

window.onload = function() {
    var oBtn = document.getElementById("btn1");
    var timer = null;
    var sBys = true; // 標誌:true=用戶滾動, false=JS動畫滾動
    
    window.onscroll = function() {
        if (!sBys) { clearInterval(timer); } // 用戶手動滾動時打斷動畫
        sBys = false;
    };
    
    oBtn.onclick = function() {
        timer = setInterval(function() {
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            var iSpeed = Math.floor(-scrollTop / 8); // 緩動速度:向下取整
            if (scrollTop === 0) {
                clearInterval(timer);
                return;
            }
            sBys = true; // 標記為 JS 驅動滾動
            document.documentElement.scrollTop = document.body.scrollTop = scrollTop + iSpeed;
        }, 30);
    };
};

關鍵技術點解析

  1. 緩動算法:iSpeed = -scrollTop / 8,距離越遠速度越快,越近越慢,形成自然減速效果。Math.floor 向下取整確保最終能到 0。
  2. 滾動源判斷:sBys 標誌區分用戶手動滾動與 JS 動畫滾動。用戶滾動時清除定時器,避免「搶奪」控制權導致卡頓。
  3. 雙重賦值兼容:document.documentElement.scrollTop(標準模式)與 document.body.scrollTop(怪癖模式)同時賦值,全瀏覽器兼容。
  4. 終止條件:scrollTop === 0 清除定時器,防止無限循環。

現代化優化方案

1. 原生平滑滾動(零代碼)

// CSS
html { scroll-behavior: smooth; }

// JS 一行
document.getElementById('btn1').onclick = () => window.scrollTo({top: 0, behavior: 'smooth'});

2. requestAnimationFrame 精確緩動

function smoothScrollToTop(duration = 500) {
    const startY = window.scrollY;
    const startTime = performance.now();
    const easeOutCubic = t => 1 - Math.pow(1 - t, 3);
    
    function step(now) {
        const progress = Math.min((now - startTime) / duration, 1);
        const eased = easeOutCubic(progress);
        window.scrollTo(0, startY * (1 - eased));
        if (progress < 1) requestAnimationFrame(step);
    }
    requestAnimationFrame(step);
}

3. 完整組件化(含顯隱邏輯、節流、無障礙)

class BackToTop {
    constructor(btnId, {threshold = 200, duration = 500} = {}) {
        this.btn = document.getElementById(btnId);
        this.threshold = threshold;
        this.duration = duration;
        this.init();
    }
    init() {
        this.btn.hidden = true;
        this.btn.setAttribute('aria-label', '返回頂部');
        this.btn.addEventListener('click', () => this.scrollToTop());
        window.addEventListener('scroll', () => this.onScroll(), {passive: true});
    }
    onScroll() {
        const scrollY = window.scrollY || document.documentElement.scrollTop;
        this.btn.hidden = scrollY <= this.threshold;
    }
    scrollToTop() {
        const startY = window.scrollY;
        const start = performance.now();
        const animate = now => {
            const p = Math.min((now - start) / this.duration, 1);
            window.scrollTo(0, startY * (1 - p) ** 3); // easeOutCubic
            if (p < 1) requestAnimationFrame(animate);
        };
        requestAnimationFrame(animate);
    }
}
new BackToTop('btn1');
copyright © 萬盛學電腦網 all rights reserved