「回到頂部」按鈕的邏輯其實只有兩件事:滾動超過一定距離就淡入,按下就平滑滾回頂端。
$(function () {
// 置頂按鈕的顯示/隱藏
$(window).scroll(function () {
var w_height = $(window).height(); // 瀏覽器視窗高度
var scroll_top = $(document).scrollTop(); // 捲軸距頂端的垂直距離
if (scroll_top > w_height) {
$("#goto-top").fadeIn(500);
} else {
$("#goto-top").fadeOut(500);
}
});
// 點擊回到頂端
$("#goto-top").click(function (e) {
e.preventDefault();
$(document.documentElement).animate({ scrollTop: 0 }, 200); // 部分瀏覽器靠這個
$(document.body).animate({ scrollTop: 0 }, 200); // 另一部分靠這個
});
});
#goto-top {
display: none;
position: fixed;
width: 38px;
height: 36px;
background: url(images/goto-top.png) no-repeat 0 0;
bottom: 40px;
right: 40px;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
-o-transition: all 0.2s;
transition: all 0.2s;
z-index: 9999;
}
#goto-top:hover {
background: url(images/goto-top.png) no-repeat 0 -36px;
}
觸發門檻用視窗高度。scroll_top 大於一個螢幕高度才出現按鈕,可以避免頁面剛打開就跳出來。想更早出現,把比較值改成固定數字(例如 300)即可。
要同時動兩個元素。document.documentElement 與 document.body 都得animate一次,因為不同瀏覽器實際滾動的是不同元素,只寫一個會有部分瀏覽器沒反應。
用 CSS sprite 做 hover。按鈕的兩種狀態合在同一張圖,用 background-position 的 0 與 -36px 切換,只載一張圖,沒有額外請求,也沒有換圖時的閃爍。
position: fixed 加上高 z-index。確保它永遠浮在內容之上,不會被其他區塊蓋住。
如果想讓效果更細緻,可以在 fadeIn/fadeOut 加上第三個參數做純淡入淡出,或改用 slideToggle 讓它從邊緣滑出。