js实现内容滚动
使用 scrollTo 方法实现平滑滚动
通过 window.scrollTo 方法实现滚动到指定位置,可配置平滑滚动效果。
window.scrollTo({
top: 500, // 滚动到的垂直位置
behavior: 'smooth' // 启用平滑滚动
});
使用 scrollBy 方法实现相对滚动
scrollBy 基于当前位置滚动指定距离,适合增量滚动场景。
window.scrollBy({
top: 200, // 向下滚动200px
behavior: 'smooth'
});
使用 Element.scrollIntoView 滚动到元素
将特定元素滚动到视口内,支持对齐方式和平滑滚动。
document.getElementById('target').scrollIntoView({
behavior: 'smooth',
block: 'start' // 对齐到视口顶部
});
自定义动画实现滚动
通过 requestAnimationFrame 实现自定义滚动动画,控制滚动速度和轨迹。
function smoothScrollTo(targetY, duration = 1000) {
const startY = window.scrollY;
const distance = targetY - startY;
let startTime = null;
function animation(currentTime) {
if (!startTime) startTime = currentTime;
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, startY + distance * progress);
if (progress < 1) requestAnimationFrame(animation);
}
requestAnimationFrame(animation);
}
smoothScrollTo(800);
监听滚动事件
通过 onscroll 事件监听滚动行为,实现动态效果(如隐藏导航栏)。
window.addEventListener('scroll', () => {
const scrollPosition = window.scrollY;
if (scrollPosition > 300) {
document.querySelector('.navbar').classList.add('hidden');
} else {
document.querySelector('.navbar').classList.remove('hidden');
}
});
横向滚动实现
通过修改 scrollLeft 属性实现横向滚动,适用于轮播图等场景。
const container = document.querySelector('.horizontal-scroll');
container.scrollTo({
left: 300,
behavior: 'smooth'
});
注意事项
- 平滑滚动需浏览器支持
behavior: 'smooth',旧版浏览器需使用 polyfill。 - 频繁触发滚动事件可能导致性能问题,建议使用防抖(debounce)优化。
- 移动端可能存在滚动延迟,可通过 CSS 属性
-webkit-overflow-scrolling: touch改善体验。







