怎么实现“点击回到顶部”的功能?
参考答案
核心两件事:判断何时显示按钮 + 平滑滚回顶部。
基础实现
<button id="toTop" aria-label="回到顶部">↑</button>
const btn = document.getElementById('toTop');
// 1) 显隐:用 IntersectionObserver 监听首屏哨兵,比 scroll 事件省性能
const sentinel = document.querySelector('#top-sentinel');
new IntersectionObserver(([entry]) => {
btn.classList.toggle('show', !entry.isIntersecting);
}, { rootMargin: '0px' }).observe(sentinel);
// 2) 滚动:scrollTo 原生平滑
btn.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
兼容与细节
- 低版本浏览器不支持
behavior: 'smooth',用requestAnimationFrame手写缓动:
function scrollToTop(duration = 300) {
const start = window.scrollY, t0 = performance.now();
const ease = t => 1 - Math.pow(1 - t, 3);
(function step(now) {
const p = Math.min(1, (now - t0) / duration);
window.scrollTo(0, start * (1 - ease(p)));
if (p < 1) requestAnimationFrame(step);
})(t0);
}
- 兼容旧内核:
document.documentElement.scrollTop = 0或document.body.scrollTop = 0(怪异模式下在 body 上)。 - 用
scroll事件时要加节流并声明{ passive: true };IntersectionObserver方案无需节流。 - 滚动容器不是 window 时(如内部
overflow: auto的列表),对容器调scrollTo或用scrollIntoView({ behavior:'smooth' })。 - 无障碍:按钮要有
aria-label,滚动后让焦点回到页面顶部;尊重prefers-reduced-motion,此时直接跳转不动画。