長頁面裡,「回到頂部」按鈕幾乎是標配。它看似簡單,但要做好有幾個細節值得講清楚:按鈕什麼時候出現、捲動要不要有動畫、以及 Safari 與 Chrome 對 html/body 選擇器的處理差異。
先準備一段夠長的內容把頁面撐開,再加一顆按鈕:
<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>回到頂部範例</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div class="a">
……這裡放大量文字內容,讓頁面高度超過一個視窗……
</div>
<input type="button" class="scrollTop" value="回到頂部">
</body>
</html>
$(function() {
$(".scrollTop").click(function() {
$('html, body').animate({ scrollTop: 0 }, 'slow');
});
});
關鍵在 $('html, body') 為什麼要同時選兩個元素。原因是各家瀏覽器對「真正持有捲軸的元素」認定不同:有的把捲動值放在 document.documentElement(即 html),有的放在 body。一次選兩個,動畫會作用在其中真正有效的那一個,另一個則無害地被忽略。若只寫 $('body'),在某些瀏覽器上會完全沒反應。
把同一套邏輯反過來即可,目標值改成文件總高度減去視窗高度:
$(".scrollBottom").click(function() {
$('html, body').animate({
scrollTop: $(document).height() - $(window).height()
}, 'slow');
});
頁面很短時顯示「回到頂部」按鈕毫無意義。加上捲動偵聽,讓它在離開頂部一段距離後才淡入:
$(function() {
var $btn = $(".scrollTop");
$btn.hide();
$(window).on('scroll', function() {
if ($(window).scrollTop() > 300) {
$btn.fadeIn(200);
} else {
$btn.fadeOut(200);
}
});
$btn.on('click', function() {
$('html, body').animate({ scrollTop: 0 }, 500);
});
});
捲動事件要節流。 scroll 的觸發頻率非常高,每次都跑一次 fadeIn/fadeOut 會造成不必要的樣式重算。用計時器或 requestAnimationFrame 節流,是低成本高收益的做法。
鍵盤無障礙。 若使用 <a> 而非 <input> 作為按鈕,請保留真實的 href="#top" 並在點擊時 return false,讓螢幕閱讀器與鍵盤使用者也能操作;同時記得給按鈕加上語意清楚的 aria-label。
最後,如果用 CSS 就能解決,也別忘了 html { scroll-behavior: smooth; } 這一行——它能在完全不寫 JavaScript 的情況下,讓頁內跳轉自帶平滑捲動效果。