人性化返回頂部鏈接三要素:常駐視覺區、平滑滾動、智能顯隱。用 jQuery 輕鬆實現,告別複製貼上。
<body id="top">
<p id="back-to-top"><a href="#top"><span></span>返回頂部</a></p>
</body>
點擊即跳轉至 body#top,無 JS 亦可用(漸進增強)。
<span> 用於承載箭頭圖標背景。position:fixed; bottom:100px; left:80px; 鎖定視窗位置。文字與圖標背景色同步過渡(1s),hover 變深灰。
p#back-to-top { position:fixed; bottom:100px; left:80px; }
p#back-to-top a { text-align:center; text-decoration:none; color:#d1d1d1; display:block; width:80px;
-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:80px; width:80px; margin-bottom:5px;
-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; }

#back-to-topfadeIn(1500);否則 fadeOut(1500)$('body,html').animate({scrollTop:0}, 1000) 平滑回頂,return false 阻止鏈接默認跳轉<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#back-to-top").hide();
$(window).scroll(function(){
if ($(window).scrollTop() > 100) $("#back-to-top").fadeIn(1500);
else $("#back-to-top").fadeOut(1500);
});
$("#back-to-top").click(function(){
$('body,html').animate({scrollTop:0}, 1000);
return false;
});
});
</script>
保留 body id="top",無 JS 環境下原生錨點跳轉依然生效。jQuery 可定位任意位置,兼容性無憂。
(來源:飛魚的聲納)