本文提供一套完整的「返回頂部」浮動組件,包含 CSS 樣式、jQuery 滾動動畫、鼠標懸停自動滾動、點擊平滑跳轉三大功能,兼容主流瀏覽器。
/* 容器固定定位 */
#shangxia { position: fixed; top: 60%; right: 50%; margin-right: -543px; display: block; }
/* 圖標通用樣式 */
#shang, #comt, #xia {
background: url(images/sprite.png) no-repeat;
position: relative; cursor: pointer; height: 25px; width: 29px; margin: 10px 0 0;
}
/* 背景定位 */
#shang { background-position: 0 -308px; }
#comt { background-position: 0 -338px; height: 32px; }
#xia { background-position: 0 -376px; }
/* 懸停態 */
#shang:hover { background-position: -31px -308px; }
#comt:hover { background-position: -31px -338px; }
#xia:hover { background-position: -31px -376px; }
jQuery(document).ready(function($) {
// 兼容獲取可滾動容器
$body = (window.opera) ?
(document.compatMode == 'CSS1Compat' ? $('html') : $('body'))
: $('html,body');
// 返回頂部:懸停緩慢滾動 + 點擊動畫
$('#shang').mouseover(function() { up(); })
.mouseout(function() { clearTimeout(fq); })
.click(function() { $body.animate({scrollTop: 0}, 400); });
// 返回底部
$('#xia').mouseover(function() { dn(); })
.mouseout(function() { clearTimeout(fq); })
.click(function() { $body.animate({scrollTop: $(document).height()}, 400); });
// 跳轉評論區
$('#comt').click(function() {
$body.animate({scrollTop: $('#comments').offset().top}, 400);
});
});
// 懸停緩慢滾動函數
function up() {
$wd = jQuery(window);
$wd.scrollTop($wd.scrollTop() - 1);
fq = setTimeout('up()', 50);
}
function dn() {
$wd = jQuery(window);
$wd.scrollTop($wd.scrollTop() + 1);
fq = setTimeout('dn()', 50);
}
<div id="shangxia">
<div id="shang" title="返回頂部"></div>
<div id="comt" title="跳轉評論"></div>
<div id="xia" title="返回底部"></div>
</div>
<!-- 頁面內容需包含 id="comments" 的評論區 -->
現代優化: 可使用 CSS
scroll-behavior: smooth替代 JS 動畫,IntersectionObserver 控制顯示/隱藏,精靈圖改用 SVG/Font Icon。