<style>
.rTop {
width: 100px; height: 25px; line-height: 25px; text-align: center;
border: 1px solid #999; border-bottom-color: #333; border-right-color: #333;
position: fixed; right: 0; bottom: 0; margin: 5px; cursor: pointer; display: none;
}
</style>
<div class="rTop" id="rTop" onclick="toTop()">返回頂部</div>
<script>
// 滾動監聽:超過 0 顯示,否則隱藏
window.onscroll = function() {
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
document.getElementById('rTop').style.display = scrollTop > 0 ? 'block' : 'none';
};
// 點擊平滑返回頂部
function toTop() {
window.scrollTo(0, 0); // 瞬間跳轉
document.getElementById('rTop').style.display = 'none';
}
</script>
position: fixed; right: 0; bottom: 0; 相對視口固定,不隨滾動移動。document.documentElement.scrollTop(標準模式)兼容 document.body.scrollTop(怪癖模式)。scrollTop > 0 切換 display。html { scroll-behavior: smooth; } /* 一行搞定,現代瀏覽器支持 */
配合 window.scrollTo({top: 0, behavior: 'smooth'}) 可控制單次滾動行為。
function smoothScrollToTop(duration = 500) {
const start = window.scrollY;
const startTime = performance.now();
function step(now) {
const progress = Math.min((now - startTime) / duration, 1);
const ease = 1 - Math.pow(1 - progress, 3); // easeOutCubic
window.scrollTo(0, start * (1 - ease));
if (progress < 1) requestAnimationFrame(step);
else document.getElementById('rTop').style.display = 'none';
}
requestAnimationFrame(step);
}
let ticking = false;
window.addEventListener('scroll', () => {
if (!ticking) {
requestAnimationFrame(() => {
const scrollTop = window.scrollY || document.documentElement.scrollTop;
document.getElementById('rTop').style.display = scrollTop > 100 ? 'block' : 'none';
ticking = false;
});
ticking = true;
}
}, {passive: true});
passive: true 告知瀏覽器不調用 preventDefault,優化滾動性能。
aria-label="返回頂部"、role="button"、tabindex="0" 支持鍵盤操作。Enter/Space 鍵盤觸發。