長頁面滾動時固定右側「回頂部」按鈕是標配交互。本文提供一個模組化、相對容器定位(非fixed)、兼容IE6、帶淡入淡出動畫的完整實現方案,並解析核心邏輯。
#container)絕對定位,緊貼容器右側,隨視口寬度變化不遮擋內容;<div id="container">
<!-- 頁面主內容 -->
</div>
.go-top {
width: 25px; height: 65px;
position: absolute; right: -30px; /* 探出容器右側 */
display: none; /* 初始隱藏,JS控制顯示 */
}
.go-top a {
display: block; cursor: pointer; outline: none;
}
.go-top img { border: 0; vertical-align: top; }
$(function() {
var topDistance = 450; // 按鈕距文檔頂部基準距離
var showDistance = 100; // 滾動超過此值顯示按鈕
var gotopHtml = "<div class='go-top'><a href='#'><img src='images/gotop.gif' /></a></div>";
// 1. 容器相對定位 + 注入按鈕
$('#container').css('position', 'relative').append(gotopHtml);
var $goTop = $('.go-top');
// 2. 初始位置計算
var updatePosition = function() {
var scrollTop = $(window).scrollTop();
$goTop.css('top', scrollTop + topDistance);
// 3. 顯隱邏輯
$goTop[scrollTop > showDistance ? 'fadeIn' : 'fadeOut']('fast');
};
// 4. 滾動監聽節流(建議加節流,此處簡化)
$(window).scroll(updatePosition);
updatePosition(); // 初始化
// 5. 平滑回頂
$goTop.find('a').click(function(e) {
e.preventDefault();
$('html, body').animate({ scrollTop: 0 }, 'fast');
});
});
#container{position:relative} + .go-top{position:absolute; right:-30px} 實現「緊貼容器右緣」而非視口右緣,響應式佈局下不遮擋內容;position:fixed,但支持position:absolute配合scroll事件計算top模擬固定效果;fadeIn/Out('fast') + animate({scrollTop:0}) 提供連貫反饋;requestAnimationFrame或lodash.throttle節流scroll事件,減少重排。prefers-reduced-motion媒體查詢尊重用戶減弱動畫偏好;