長頁面閱讀到一半想回頭看目錄,總不能一直滾滾輪。「回到頂部」按鈕就是為了解這個痛點而生:滾到一定深度才出現,點一下平滑回到頁首。實作上 HTML 一行、CSS 負責樣式與過渡、JS 負責顯示時機與滾動動畫,分工非常清楚。

<p id="back-to-top"><a href="#top"><span></span></a></p>
p#back-to-top {
position: fixed;
bottom: 100px;
right: 80px;
}
p#back-to-top a {
text-align: center;
text-decoration: none;
color: #d1d1d1;
display: block;
width: 30px;
/* 用 CSS3 的 transition 為連結文字加上漸變效果 */
-moz-transition: color 1s;
-webkit-transition: color 1s;
-o-transition: color 1s;
}
p#back-to-top a:hover {
color: #979797;
}
p#back-to-top a span {
background: #d1d1d1 url(../images/arrow_up.png) no-repeat center center;
border-radius: 6px;
display: block;
height: 30px;
width: 30px;
margin-bottom: 5px;
/* 同樣用 transition 為 span 的背景色加上漸變 */
-moz-transition: background 1s;
-webkit-transition: background 1s;
-o-transition: background 1s;
}
#back-to-top a:hover span {
background: #979797 url(../images/arrow_up.png) no-repeat center center;
}
幾個著力點:用 position: fixed 讓按鈕固定在右下角視窗位置,不隨頁面滾動;border-radius 做出圓角方塊;再用 transition 讓 hover 的顏色變化柔和一點,而不是硬邦邦地瞬間切換。
<script type="text/javascript">
$(document).ready(function () {
// 一開始先隱藏
$("#back-to-top").hide();
// 滾動超過 600px 才出現,否則淡出
$(function () {
$(window).scroll(function () {
if ($(window).scrollTop() > 600) {
$("#back-to-top").fadeIn(500);
} else {
$("#back-to-top").fadeOut(500);
}
});
// 點擊後平滑回到頁面頂部
$("#back-to-top").click(function () {
$('body,html').animate({ scrollTop: 0 }, 500);
return false;
});
});
});
</script>
$('body,html') 要一起選。不同瀏覽器滾動的實際元素不同,只寫其中一個會有相容問題。return false 別漏掉,否則 href="#top" 會觸發瞬移,把平滑動畫的效果抵銷掉。window.addEventListener('scroll', ...) 搭配 window.scrollTo({ top: 0, behavior: 'smooth' }) 達到同樣效果,並注意為 scroll 事件加上節流(throttle)以維持效能。以上就是本文的全部內容,希望對大家的學習有所幫助。