<a href="#top" id="backTop" class="back-top" aria-label="返回頂部" role="button">
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M7 14l5-5 5 5"/></svg>
</a>
<main id="top">...頁面內容...</main>
.back-top {
position: fixed; right: 24px; bottom: 24px; z-index: 999;
width: 48px; height: 48px; border-radius: 50%;
background: #333; color: #fff;
display: flex; align-items: center; justify-content: center;
opacity: 0; visibility: hidden; transform: translateY(20px);
transition: opacity .3s, visibility .3s, transform .3s;
text-decoration: none;
}
.back-top.visible {
opacity: 1; visibility: visible; transform: translateY(0);
}
.back-top:hover { background: #555; }
.back-top:focus { outline: 3px solid #4af; outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) {
.back-top { transition: none; }
html { scroll-behavior: auto; }
}
(function() {
var btn = document.getElementById('backTop');
var threshold = 200;
var rafId = null;
function onScroll() {
if (rafId) return;
rafId = requestAnimationFrame(function() {
var scrollY = window.scrollY || document.documentElement.scrollTop;
btn.classList.toggle('visible', scrollY > threshold);
rafId = null;
});
}
function onClick(e) {
e.preventDefault();
var target = document.getElementById('top') || document.body;
// 原生平滑滾動
target.scrollIntoView({behavior: 'smooth', block: 'start'});
// 降級:手動動畫
// smoothScrollTo(0, 500);
}
window.addEventListener('scroll', onScroll, {passive: true});
btn.addEventListener('click', onClick);
// 鍵盤無障礙:Enter/Space 觸發
btn.addEventListener('keydown', function(e) {
if (e.key === 'Enter' || e.key === ' ') { onClick(e); }
});
})();
function smoothScrollTo(targetY, duration) {
var startY = window.scrollY;
var diff = targetY - startY;
var startTime = performance.now();
function step(now) {
var t = Math.min(1, (now - startTime) / duration);
var eased = t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t; // easeInOutQuad
window.scrollTo(0, startY + diff * eased);
if (t < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
html { scroll-behavior: smooth; }
.back-top { /* 僅控制顯隱 */ }
配合 @media (prefers-reduced-motion: reduce) 尊重使用者動畫偏好。