你應該見過很多網站在頁面右下角有個「回到頂端」的懸浮按鈕——頁面開始時它是隱藏的,一旦滾動滾動條就出現,回到頂端後又重新消失。這種細節能顯著提升長頁面的使用體驗。以下分享控制這個效果的 JS 代碼。
效果示意:

控制的 JS 代碼如下:
function goTop(){
var _btn = document.getElementById("goTop");
if (document.documentElement && document.documentElement.scrollTop) {
var _con = document.documentElement;
} else if (document.body) {
var _con = document.body;
}
window.onscroll = set;
_btn.style.left = document.documentElement.scrollWidth/2 + 500 + "px";
_btn.onclick = function (){
_btn.style.display = "none";
window.onscroll = null;
this.timer = setInterval(function() {
_con.scrollTop -= Math.ceil(_con.scrollTop * 0.3);
if (_con.scrollTop == 0) clearInterval(_btn.timer, window.onscroll = set);
}, 10);
};
function set() {
_btn.style.display = _con.scrollTop ? 'block': "none";
}
};
document.write("<div id=\"goTop\" style=\"font-size:12px; width:20px; height:55px; background:#0950A2; color:#fff; line-height:14px; position:fixed; bottom:30px; display:none; cursor:pointer; text-align:center; padding:5px 0; z-index:1; _position:absolute; _top:expression(eval(document.compatMode && document.compatMode == 'CSS1Compat') ? documentElement.scrollTop + (documentElement.clientHeight - this.clientHeight) - 30 : document.body.scrollTop + (document.body.clientHeight - this.clientHeight) - 30);\">返<br />回<br />頂<br />部</div>");
window.onscroll = goTop;
這個實現的巧妙之處在於:透過 onscroll 事件實時監聽滾動位置,控制按鈕的顯示與隱藏;點擊按鈕時,用 setInterval 週期性地將 scrollTop 乘以 0.3 逐次遞減,形成一種「先快後慢」的緩動回頂效果,比單純的固定步長滾動更為自然流暢。代碼中還透過 CSS expression 兼容了舊版 IE 的定位問題。