無依賴、可直接複製使用的返回頂部組件,包含滾動監聽節流、淡入淡出、平滑滾動動畫。
<a href="#" id="toTop" title="返回頂部">↑</a>
#toTop {
position: fixed;
right: 20px;
bottom: 20px;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
background: rgba(0,0,0,0.5);
color: #fff;
border-radius: 4px;
text-decoration: none;
opacity: 0;
visibility: hidden;
transition: opacity 0.3s, visibility 0.3s;
z-index: 9999;
}
#toTop.visible {
opacity: 1;
visibility: visible;
}
(function() {
var toTop = document.getElementById('toTop');
var scrollTimer = null;
// 滾動監聽(節流 100ms)
window.addEventListener('scroll', function() {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function() {
var st = window.pageYOffset || document.documentElement.scrollTop;
toTop.classList.toggle('visible', st > 200);
}, 100);
}, {passive: true});
// 點擊平滑滾動
toTop.addEventListener('click', function(e) {
e.preventDefault();
window.scrollTo({top: 0, behavior: 'smooth'});
});
})();
setTimeout 合併高頻 scroll 事件,避免主線程阻塞。{passive: true} 告訴瀏覽器不調用 preventDefault,提升滾動性能。transition,JS 僅切換 class。scrollTo({behavior:'smooth'}) 原生實現,無需手寫動畫循環。將上述代碼放入頁面底部 <script> 中即可生效,兼容所有現代瀏覽器。