<!-- 放置頁面任意位置,配合 CSS 美化 -->
<p id="back-to-top"><a href="#top"><span></span>回到頂部</a></p>
#back-to-top {
position: fixed;
bottom: 30px;
right: 30px;
display: none; /* JS 會控制顯示/隱藏 */
z-index: 999;
}
#back-to-top a {
display: block;
width: 50px;
height: 50px;
background: rgba(0,0,0,0.6);
color: #fff;
text-align: center;
line-height: 50px;
border-radius: 4px;
text-decoration: none;
}
#back-to-top a:hover { background: rgba(0,0,0,0.8); }
<script src="js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function() {
var $backToTop = $('#back-to-top');
// 初始隱藏
$backToTop.hide();
// 捲動監聽:超過 100px 顯示
$(window).scroll(function() {
if ($(window).scrollTop() > 100) {
$backToTop.fadeIn(1500);
} else {
$backToTop.fadeOut(1500);
}
});
// 點擊平滑捲動回頂部
$backToTop.click(function(e) {
e.preventDefault(); // 取消錨點預設跳躍
$('body, html').animate({ scrollTop: 0 }, 1000);
return false;
});
});
</script>
requestAnimationFrame 或 setTimeout 節流,避免高頻觸發效能負擔。transition: opacity 0.3s + class 切換,效能優於 jQuery fadeIn/Out。<button> 而非 <a>,無障礙更友善。此元件可直接複製套用於任何專案,若需支援 IE8 以下請確認 jQuery 版本 (1.x 支援 IE6+)。