博客園風格固定右下角返回頂部按鈕:CSS position:fixed 定位 + JS 平滑滾動動畫,兼容主流瀏覽器。
#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); }
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);
});
<button id="backToTop" title="返回頂部">▲</button>
requestAnimationFrame 或 setTimeout 節流,避免高頻觸發。aria-label="返回頂部"、鍵盤可聚焦 (tabindex="0")、Enter/Space 觸發。// 視口尺寸
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