萬盛學電腦網

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

JavaScript 實現頁面右下角固定「返回頂部」按鈕

博客園風格固定右下角返回頂部按鈕:CSS position:fixed 定位 + JS 平滑滾動動畫,兼容主流瀏覽器。

CSS 固定定位

#backToTop {
  position: fixed;      /* 相對視口固定 */
  right: 20px; bottom: 20px;
  width: 50px; height: 50px;
  background: rgba(0,0,0,0.5); color: #fff;
  border-radius: 50%; cursor: pointer;
  display: flex; align-items: center; justify-content: center;
  font-size: 20px; line-height: 1;
  z-index: 999;
  opacity: 0; visibility: hidden;
  transition: opacity 0.3s, visibility 0.3s;
}
#backToTop.show { opacity: 1; visibility: visible; }
#backToTop:hover { background: rgba(0,0,0,0.8); }

JS 滾動監聽與平滑回頂

var btn = document.getElementById('backToTop');
var scrollTimer;

// 滾動顯示/隱藏
window.addEventListener('scroll', function() {
  if (window.pageYOffset > 200) {
    btn.classList.add('show');
  } else {
    btn.classList.remove('show');
  }
});

// 點擊平滑滾動到頂部
btn.addEventListener('click', function() {
  // 現代瀏覽器原生平滑滾動
  if ('scrollBehavior' in document.documentElement.style) {
    window.scrollTo({ top: 0, behavior: 'smooth' });
    return;
  }
  
  // 降級:JS 動畫實現
  var start = window.pageYOffset;
  var startTime = Date.now();
  var duration = 500; // ms
  
  function animate() {
    var elapsed = Date.now() - startTime;
    var progress = Math.min(elapsed / duration, 1);
    // 緩動函數
    var ease = 1 - Math.pow(1 - progress, 3);
    window.scrollTo(0, start * (1 - ease));
    if (progress < 1) requestAnimationFrame(animate);
  }
  requestAnimationFrame(animate);
});

HTML

<button id="backToTop" title="返回頂部">▲</button>

進階優化

  • 節流滾動事件: 使用 requestAnimationFrame 或 setTimeout 節流,避免高頻觸發。
  • IntersectionObserver: 觀察頁腳元素進入視口時顯示按鈕,比 scroll 事件更高效。
  • 無障礙: 添加 aria-label="返回頂部"、鍵盤可聚焦 (tabindex="0")、Enter/Space 觸發。
  • 移動端適配: 增大點擊區域,考慮安全區域 (safe-area-inset-bottom)。

相關幾何屬性速查

// 視口尺寸
window.innerWidth / innerHeight
document.documentElement.clientWidth / clientHeight

// 文檔尺寸
document.body.scrollWidth / scrollHeight
document.documentElement.scrollWidth / scrollHeight

// 滾動位置
window.pageYOffset / pageXOffset
document.documentElement.scrollTop / scrollLeft
document.body.scrollTop / scrollLeft (兼容舊版)

// 螢幕尺寸
screen.width / height
screen.availWidth / availHeight
copyright © 萬盛學電腦網 all rights reserved