js实现上下滚动
实现上下滚动的 JavaScript 方法
使用 window.scrollTo()
通过 window.scrollTo() 方法实现滚动到指定位置。可以设置平滑滚动效果。
// 滚动到页面顶部
window.scrollTo({
top: 0,
behavior: 'smooth'
});
// 滚动到页面底部
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth'
});
使用 Element.scrollIntoView()
让某个元素滚动到可视区域内,支持平滑滚动。
const element = document.getElementById('targetElement');
element.scrollIntoView({
behavior: 'smooth',
block: 'start' // 或 'end', 'center'
});
监听滚动事件
通过监听滚动事件实现自定义滚动逻辑,例如显示/隐藏返回顶部按钮。
window.addEventListener('scroll', function() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const backToTopButton = document.getElementById('backToTop');
if (scrollTop > 300) {
backToTopButton.style.display = 'block';
} else {
backToTopButton.style.display = 'none';
}
});
自定义滚动动画
通过 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);
}
// 调用示例
scrollToTop(1000); // 1秒内滚动到顶部
使用 CSS Scroll Snap
结合 CSS 的 scroll-snap-type 和 scroll-snap-align 实现分块滚动。
.container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
height: 100vh;
}
.section {
scroll-snap-align: start;
height: 100vh;
}
注意事项
- 平滑滚动效果需浏览器支持
behavior: 'smooth',旧版本浏览器需使用 polyfill。 - 移动端滚动需考虑触摸事件和性能优化。
- 避免频繁触发滚动事件,可使用防抖(debounce)或节流(throttle)优化性能。







