js实现向上滚动
使用 window.scrollTo 方法
通过 window.scrollTo 方法可以平滑滚动到页面顶部。传递 { top: 0, behavior: 'smooth' } 作为参数可以实现平滑滚动效果。
window.scrollTo({
top: 0,
behavior: 'smooth'
});
使用 Element.scrollIntoView 方法
选择一个页面顶部的元素(如 document.body 或 document.documentElement),调用 scrollIntoView 方法并设置 behavior: 'smooth'。

document.body.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
使用 requestAnimationFrame 自定义动画
通过逐步修改 scrollTop 值实现自定义滚动动画,适合需要更精细控制的场景。

function scrollToTop() {
const duration = 1000; // 动画持续时间(毫秒)
const start = window.pageYOffset;
const startTime = performance.now();
function animateScroll(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, start * (1 - progress));
if (progress < 1) {
requestAnimationFrame(animateScroll);
}
}
requestAnimationFrame(animateScroll);
}
scrollToTop();
使用 CSS scroll-behavior 属性
在 CSS 中为根元素设置 scroll-behavior: smooth,之后调用 window.scrollTo 或链接跳转时会自动平滑滚动。
html {
scroll-behavior: smooth;
}
// 无需额外配置,直接调用即可
window.scrollTo(0, 0);
监听按钮点击事件
为“返回顶部”按钮绑定点击事件,触发上述任意滚动方法。
<button id="backToTop">返回顶部</button>
document.getElementById('backToTop').addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
兼容性提示
behavior: 'smooth'在 IE 和部分旧版浏览器中不支持,需使用 polyfill 或自定义动画。scroll-behavior: smooth同样需检查浏览器兼容性。






