如今很多網站都加入了「返回頂部」功能,最偷懶的做法是直接寫一個鏈到 # 的 a 標籤。今天抽空用原生 JavaScript 手寫了兩種實現,分享出來供大家參考,若有不足之處歡迎指正。
HTML 結構與樣式:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>js-回到頂部</title>
<style type="text/css">
*{margin:0;padding:0;}
.wrapper{width:960px;margin-left:auto;margin-right:auto;}
p{margin:10px;line-height:30px;}
#top{position:fixed;right:130px;bottom:50px;background:gray;padding:5px;display:block;}
</style>
</head>
<body>
<!-- 這裡放置大量段落文字以撐高頁面 -->
<a href="javascript:;" id="top">回到頂部</a>
</body>
</html>
<script type="text/javascript" src="js/toTop.js"></script>
<script type="text/javascript">
window.onload = function () {
toTop('top', false);
}
</script>
toTop.js 代碼:
// 第一個參數是按鈕 id;第二個參數是布爾值,
// true 表示一直顯示按鈕,false 表示滾動距離不為 0 時才顯示
function toTop(id, show) {
var oTop = document.getElementById(id);
var bShow = show;
if (!bShow) {
oTop.style.display = 'none';
setTimeout(btnShow, 50);
}
oTop.onclick = scrollToTop;
function scrollToTop() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var iSpeed = Math.floor(-scrollTop / 2);
if (scrollTop <= 0) {
if (!bShow) { oTop.style.display = 'none'; }
return;
}
document.documentElement.scrollTop = document.body.scrollTop = scrollTop + iSpeed;
setTimeout(arguments.callee, 50);
}
function btnShow() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop <= 0) {
oTop.style.display = 'none';
} else {
oTop.style.display = 'block';
}
setTimeout(arguments.callee, 50);
}
}
注意:IE6 下 position:fixed 無效,具體兼容處理需自行解決。
這種寫法的思路是每次取當前滾動距離的一半作為速度上移,距離越小速度越慢,形成一種減速滑動的視覺效果。
原理是:先獲取滾動條到頁面頂部的距離,然後按比例上移一段;再獲取距離,再上移一段(幅度比上次更小);如此反覆遞歸,直到距離歸零。
<script type="text/javascript">
/**
* 回到頁面頂部
* @param acceleration 加速度
* @param time 時間間隔(毫秒)
*/
function goTop(acceleration, time) {
acceleration = acceleration || 0.1;
time = time || 16;
var x1 = 0, y1 = 0, x2 = 0, y2 = 0, x3 = 0, y3 = 0;
if (document.documentElement) {
x1 = document.documentElement.scrollLeft || 0;
y1 = document.documentElement.scrollTop || 0;
}
if (document.body) {
x2 = document.body.scrollLeft || 0;
y2 = document.body.scrollTop || 0;
}
x3 = window.scrollX || 0;
y3 = window.scrollY || 0;
// 滾動條到頁面頂部的水平與垂直距離
var x = Math.max(x1, Math.max(x2, x3));
var y = Math.max(y1, Math.max(y2, y3));
// 滾動距離 = 目前距離 / 速度,距離越小速度越大,滾動幅度越來越小
var speed = 1 + acceleration;
window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));
// 距離不為零則繼續迭代
if (x > 0 || y > 0) {
var invokeFunction = "goTop(" + acceleration + ", " + time + ")";
window.setTimeout(invokeFunction, time);
}
}
</script>
需要說明的是,document.documentElement.scrollTop、document.body.scrollTop、window.scrollY 本質上都是獲取滾動距離,但各自只在不同瀏覽器中生效,這裡用 Math.max 取最大值來兼容各瀏覽器。
使用方式:
<a href="#" onclick="goTop();return false;">TOP</a>