js如何实现滑动效果
使用CSS的scroll-behavior属性
在CSS中设置scroll-behavior: smooth可以让滚动行为变得平滑。这种方法简单且无需JavaScript,但兼容性有限(IE不支持)。
html {
scroll-behavior: smooth;
}
使用Element.scrollIntoView()
通过调用DOM元素的scrollIntoView()方法并设置behavior: 'smooth'实现平滑滚动。

document.getElementById('target').scrollIntoView({
behavior: 'smooth'
});
使用window.scrollTo()
通过window.scrollTo()方法实现页面滚动,结合behavior: 'smooth'选项。
window.scrollTo({
top: 1000,
behavior: 'smooth'
});
使用requestAnimationFrame自定义动画
手动实现滚动动画,通过计算步长和requestAnimationFrame逐帧更新滚动位置。

function smoothScrollTo(targetY, duration = 1000) {
const startY = window.pageYOffset;
const distance = targetY - startY;
let startTime = null;
function animation(currentTime) {
if (startTime === null) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const progress = Math.min(timeElapsed / duration, 1);
window.scrollTo(0, startY + distance * progress);
if (timeElapsed < duration) requestAnimationFrame(animation);
}
requestAnimationFrame(animation);
}
// 调用示例
smoothScrollTo(500);
使用第三方库(如animate-scroll)
通过引入第三方库简化实现。例如使用animate-scroll库:
import { animateScroll } from 'animate-scroll';
animateScroll.scrollTo(500, {
duration: 1000,
easing: 'easeInOutQuad'
});
监听滚动事件实现视差效果
结合scroll事件和CSS变换实现视差滚动效果。
window.addEventListener('scroll', function() {
const scrollY = window.pageYOffset;
document.querySelector('.parallax-element').style.transform =
`translateY(${scrollY * 0.5}px)`;
});
注意事项
- 自定义动画时注意性能优化,避免频繁触发重排。
- 移动端需考虑
passive事件监听器以减少滚动延迟。 - 部分方法需配合CSS的
overflow属性使用。





