「返回頂部」按鈕應該只在需要的時候出現。頁面頂端本來就看得到導航,按鈕放在那裡是多餘的;往下捲得越遠,它的價值才越高。以下用滾輪事件判斷位置來控制顯示。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>實現動態的顯示回到頂部與否</title>
<style>
.back_top {
width: 45px; height: 45px;
background: url(back_top_new.png) 0 0;
position: fixed; left: 50%; margin-left: 500px; bottom: 105px;
display: none;
}
.back_top:hover { background: url(images/back_top_new.png) 0 -46px; }
</style>
</head>
<body>
<a title="返回頂部" href="javascript:void(0)" class="back_top"></a>
<script src="js/jquery-1.11.0.min.js"></script>
<script>
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";
function toggleBackTop() {
var t = document.body.scrollTop + document.documentElement.scrollTop;
$(".back_top").css("display", t == 0 ? "none" : "block");
}
if (document.attachEvent) { // IE 與部分 Opera 設定
document.attachEvent("on" + mousewheelevt, toggleBackTop);
} else if (document.addEventListener) { // 標準瀏覽器
document.addEventListener(mousewheelevt, toggleBackTop, false);
}
</script>
</body>
</html>
這段程式有幾個結構性問題,值得逐一說明。
第一,滾輪事件不涵蓋所有捲動方式。使用者拖曳捲軸、按空白鍵與方向鍵、用觸控板雙指滑動、或點擊連結跳到頁尾,都不會觸發 mousewheel。按鈕的顯示狀態因此會與實際位置不符。
第二,Firefox 的判斷方式有缺陷。用 navigator.userAgent 偵測瀏覽器既不可靠也不必要——每個事件型別都試著綁一次即可,不支援的自然不會觸發。
第三,兩個事件處理函式內容完全相同,這本身就是可以合併的訊號。
第四,href="javascript:void(0)" 是可讀性與可維護性都很差的寫法,而且螢幕閱讀器不會把它當成有意義的連結。
捲動狀態的唯一可靠來源是 scroll 事件:
window.addEventListener('scroll', function () {
var scrolled = window.scrollY || document.documentElement.scrollTop;
document.querySelector('.back_top').hidden = scrolled === 0;
}, { passive: true });
// 回到頂部
document.querySelector('.back_top').addEventListener('click', function () {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
三個改寫重點:用 scroll 取代 mousewheel 以涵蓋所有捲動來源;用 hidden 屬性或 class 切換取代直接改 style;{ passive: true } 讓瀏覽器知道這個監聽器不會呼叫 preventDefault,於是能最佳化捲動效能,不必等待回呼執行完。
另外,scroll 事件觸發頻率很高,若回呼裡有較重的運算,建議用 requestAnimationFrame 或 debounce 做節流。本例的邏輯很輕,還不需要。
用 <button> 而非 <a> 語意更準確,因為它執行動作而不是導航到某個頁面。同時給它 aria-label="返回頁面頂部",並確保它有 :focus-visible 樣式,讓只用鍵盤的使用者知道焦點在哪裡。