文章越長,讀者回到頂部的成本就越高。反覆滾動鼠標滾輪顯然不是好體驗,而在頁面右下角放一個懸浮的「返回頂部」按鈕,點一下就回到起點,這個細節能明顯提升可讀性。
思路分三步:頁面加載時把元素定位在可視區右下角;頁面滾動時持續校正它的 Y 坐標,讓它「釘」在屏幕上;點擊時把滾動距離歸零。
要點一:獲取可視區寬度需要寫兼容寫法。
var screenw = document.documentElement.clientWidth || document.body.clientWidth;
前者兼容 Chrome 等標準瀏覽器,後者兼容舊版 quirks 模式。
要點二:水平方向靠右對齊,用可視區寬度減去元素自身寬度。
oTop.style.left = screenw - oTop.offsetWidth + "px";
要點三:垂直方向要疊加滾動距離,否則元素會隨頁面一起滾走。
oTop.style.top = screenh - oTop.offsetHeight + scrolltop + "px";
要點四:點擊歸零時兩處 scrollTop 都要賦值,這同樣是為了兼容。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>返回頂部</title>
<style>
body { margin:0; padding:0; }
#to_top {
width:30px; height:40px; padding:20px;
font:14px/20px arial; text-align:center;
background:#06c; position:absolute;
cursor:pointer; color:#fff;
}
</style>
<script>
window.onload = function () {
var oTop = document.getElementById("to_top");
var screenw = document.documentElement.clientWidth || document.body.clientWidth;
var screenh = document.documentElement.clientHeight || document.body.clientHeight;
oTop.style.left = screenw - oTop.offsetWidth + "px";
oTop.style.top = screenh - oTop.offsetHeight + "px";
window.onscroll = function () {
var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
oTop.style.top = screenh - oTop.offsetHeight + scrolltop + "px";
};
oTop.onclick = function () {
document.documentElement.scrollTop = document.body.scrollTop = 0;
};
};
</script>
</head>
<body style="height:1000px;">
<h1>返回頂部</h1>
<div id="to_top">返回頂部</div>
</body>
</html>
如果想讓回頂過程更柔和,可以把 scrollTop = 0 換成緩動動畫,體驗會再上一個台階。此外,現代項目中更推薦使用 position: fixed 定位,就不需要在 scroll 事件裡手動校正坐標了。