js实现向上滚动
实现向上滚动的JavaScript方法
使用window.scrollTo()方法实现平滑向上滚动。该方法接受x和y坐标作为参数,设置滚动位置。
window.scrollTo({
top: 0,
behavior: 'smooth'
});
使用requestAnimationFrame实现自定义动画
通过递归调用requestAnimationFrame创建自定义滚动动画,可控制滚动速度和持续时间。

function scrollToTop(duration) {
const start = window.pageYOffset;
const startTime = performance.now();
function scrollStep(timestamp) {
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, start * (1 - progress));
if (progress < 1) {
window.requestAnimationFrame(scrollStep);
}
}
window.requestAnimationFrame(scrollStep);
}
// 调用示例:1秒内滚动到顶部
scrollToTop(1000);
使用CSS scroll-behavior配合JavaScript
在CSS中设置全局滚动行为,然后通过简单JavaScript触发。

html {
scroll-behavior: smooth;
}
// 只需调用即可触发平滑滚动
window.scrollTo(0, 0);
添加滚动按钮的完整实现
创建一个可交互的滚动按钮,在页面滚动一定距离后显示。
<button id="scrollTopBtn" style="display:none;">回到顶部</button>
const scrollBtn = document.getElementById('scrollTopBtn');
window.addEventListener('scroll', () => {
scrollBtn.style.display = window.pageYOffset > 300 ? 'block' : 'none';
});
scrollBtn.addEventListener('click', () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
兼容性考虑
对于不支持behavior: 'smooth'的旧浏览器,应提供polyfill或回退方案。
function smoothScrollToTop() {
if ('scrollBehavior' in document.documentElement.style) {
window.scrollTo({ top: 0, behavior: 'smooth' });
} else {
// 回退到jQuery动画或其他实现
$('html, body').animate({ scrollTop: 0 }, 600);
}
}





