效果需求
- 頁面較長時,右下角固定顯示「返回頂部」按鈕
- 滾動時按鈕位置跟隨視口右下角
- 點擊按鈕 → 頁面平滑滾動至頂部
核心座標計算
// 可視區寬高(兼容寫法)
var clientW = document.documentElement.clientWidth || document.body.clientWidth;
var clientH = document.documentElement.clientHeight || document.body.clientHeight;
// 滾動距離
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 按鈕右下角定位
btn.style.left = clientW - btn.offsetWidth + 'px';
btn.style.top = clientH - btn.offsetHeight + scrollTop + 'px';
完整代碼(原生 JS,無依賴)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>返回頂部</title>
<style>
body { margin: 0; padding: 0; height: 2000px; }
#toTop {
width: 50px; height: 50px; line-height: 50px;
background: #06c; color: #fff; text-align: center;
position: absolute; cursor: pointer; border-radius: 4px;
opacity: 0; visibility: hidden; transition: .3s;
box-shadow: 0 2px 6px rgba(0,0,0,.2);
}
#toTop.show { opacity: 1; visibility: visible; }
</style>
</head>
<body>
<h1 style="padding:20px">向下滾動頁面,右下角將出現按鈕</h1>
<div id="toTop">↑ 頂部</div>
<script>
var btn = document.getElementById('toTop');
var clientW, clientH, btnW, btnH;
function refreshLayout() {
clientW = document.documentElement.clientWidth || document.body.clientWidth;
clientH = document.documentElement.clientHeight || document.body.clientHeight;
btnW = btn.offsetWidth; btnH = btn.offsetHeight;
btn.style.left = clientW - btnW - 20 + 'px'; // 右邊留 20px
btn.style.top = clientH - btnH - 20 + 'px'; // 底部留 20px
}
window.onload = window.onresize = refreshLayout;
window.onscroll = function() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 滾動超過一屏顯示
if (scrollTop > clientH) btn.classList.add('show');
else btn.classList.remove('show');
// 固定定位跟隨(若用 fixed 可省略此行)
btn.style.top = clientH - btnH - 20 + scrollTop + 'px';
};
btn.onclick = function() {
// 平滑滾動(現代瀏覽器)
if ('scrollBehavior' in document.documentElement.style) {
window.scrollTo({ top: 0, behavior: 'smooth' });
} else {
// 降級:動畫模擬
var start = Date.now(), duration = 400;
var from = document.documentElement.scrollTop || document.body.scrollTop;
function step() {
var p = Math.min((Date.now() - start) / duration, 1);
var easing = p * (2 - p); // easeOutQuad
document.documentElement.scrollTop = document.body.scrollTop = from * (1 - easing);
if (p < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
};
</script>
</body>
</html>
關鍵優化點
- CSS fixed 定位:現代瀏覽器直接用
position: fixed; right: 20px; bottom: 20px;,無需 JS 計算滾動跟隨。
- 平滑滾動:優先用原生
scrollTo({behavior:'smooth'}),降級用 requestAnimationFrame 緩動動畫。
- 顯隱邏輯:滾動超過一屏高度才顯示,避免首屏干擾。
- 防抖/節流:
onscroll 高頻觸發,建議用 requestAnimationFrame 或 setTimeout 節流佈局計算。
- 無障礙:添加
aria-label="返回頂部"、tabindex="0"、鍵盤 Enter 觸發。