萬盛學電腦網

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

原生 JavaScript 實現平滑返回頂部按鈕

核心邏輯

使用 setInterval 定時器,每幀按比例減少 scrollTop,實現緩動效果。代碼兼容 IE6+ 及現代瀏覽器。

經典實現(兼容舊瀏覽器)


<script>
var gotoTopType = -1;  // 1=documentElement, 2=body, 0=不支援
var gotoTopTimer = 0;

function gotoTopTimer() {
    var scrollTop = gotoTopType === 1 
        ? document.documentElement.scrollTop 
        : document.body.scrollTop;
    
    // 緩動:每次減少當前距離的 15%
    var moveBy = 15;
    scrollTop -= Math.ceil(scrollTop * moveBy / 100);
    if (scrollTop < 0) scrollTop = 0;
    
    if (gotoTopType === 1) {
        document.documentElement.scrollTop = scrollTop;
    } else {
        document.body.scrollTop = scrollTop;
    }
    
    if (scrollTop === 0) {
        clearInterval(gotoTopTimer);
        gotoTopTimer = 0;
    }
}

function gotoTop() {
    if (gotoTopTimer !== 0) return; // 防止重複啟動
    
    // 檢測滾動容器
    if (document.documentElement && document.documentElement.scrollTop) {
        gotoTopType = 1;
    } else if (document.body && document.body.scrollTop) {
        gotoTopType = 2;
    } else {
        gotoTopType = 0;
    }
    
    if (gotoTopType > 0) {
        gotoTopTimer = setInterval(gotoTopTimer, 50); // 20fps
    }
}
</script>

<a href="javascript:void(0)" onclick="gotoTop()">【返回頂部】</a>

現代重寫版


function createScrollToTop(options = {}) {
    const {
        triggerOffset = 200,    // 顯示按鈕的滾動閾值
        duration = 500,         // 動畫時長(ms)
        easing = t => 1 - Math.pow(1 - t, 4), // easeOutQuart
        buttonHtml = '↑'
    } = options;
    
    // 創建按鈕
    const btn = document.createElement('button');
    btn.innerHTML = buttonHtml;
    Object.assign(btn.style, {
        position: 'fixed', right: '20px', bottom: '20px',
        width: '44px', height: '44px', borderRadius: '50%',
        background: '#333', color: '#fff', border: 'none',
        cursor: 'pointer', opacity: '0', visibility: 'hidden',
        transition: 'opacity 0.3s, visibility 0.3s',
        zIndex: 9999, fontSize: '20px', lineHeight: '44px'
    });
    document.body.appendChild(btn);
    
    // 滾動監聽
    let ticking = false;
    window.addEventListener('scroll', () => {
        if (!ticking) {
            requestAnimationFrame(() => {
                btn.style.opacity = window.scrollY > triggerOffset ? '1' : '0';
                btn.style.visibility = window.scrollY > triggerOffset ? 'visible' : 'hidden';
                ticking = false;
            });
            ticking = true;
        }
    }, { passive: true });
    
    // 點擊平滑滾動
    btn.addEventListener('click', () => {
        const start = window.scrollY;
        const startTime = performance.now();
        
        function animate(now) {
            const progress = Math.min((now - startTime) / duration, 1);
            window.scrollTo(0, start * (1 - easing(progress)));
            if (progress < 1) requestAnimationFrame(animate);
        }
        requestAnimationFrame(animate);
    });
    
    return btn;
}

// 使用
createScrollToTop({ duration: 600 });

CSS 原生方案(最簡單)


/* 僅需一行 CSS */
html { scroll-behavior: smooth; }

/* HTML 錨點 */


/* JS 僅控制顯示/隱藏 */
const btn = document.getElementById('backTop');
window.addEventListener('scroll', () => {
    btn.style.display = window.scrollY > 200 ? 'block' : 'none';
});

✅ 零依賴、性能最佳、瀏覽器原生優化
⚠️ 不支援 IE、Safari 15.4 前版本

copyright © 萬盛學電腦網 all rights reserved