js 实现滚屏
使用 window.scrollTo 方法
通过 window.scrollTo(x, y) 实现滚动到页面指定位置。x 为水平位置,y 为垂直位置。
window.scrollTo(0, 500); // 滚动到垂直位置 500px
平滑滚动效果
添加 behavior: 'smooth' 参数实现平滑滚动。
window.scrollTo({
top: 500,
behavior: 'smooth'
});
滚动到指定元素
通过 Element.scrollIntoView() 方法将元素滚动到可视区域。
document.getElementById('target').scrollIntoView({
behavior: 'smooth'
});
监听滚动事件
使用 window.addEventListener('scroll', callback) 监听页面滚动。
window.addEventListener('scroll', function() {
console.log(window.scrollY); // 输出当前垂直滚动位置
});
滚动动画实现
通过 requestAnimationFrame 实现自定义滚动动画。
function scrollToTop(duration) {
const start = window.scrollY;
const startTime = performance.now();
function animate(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, start * (1 - progress));
if (progress < 1) requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
}
scrollToTop(1000); // 1秒内滚动到顶部
使用第三方库(如 jQuery)
jQuery 提供 animate 方法简化滚动动画。

$('html, body').animate({ scrollTop: 500 }, 500); // 500ms 滚动到 500px
注意事项
- 平滑滚动可能不兼容旧版浏览器,需检查
behavior: 'smooth'支持性。 - 高频滚动事件可能影响性能,建议使用防抖(debounce)优化。
- 移动端需考虑触摸交互,避免与原生滚动冲突。






