js实现页面滚动
实现页面滚动的方法
使用 window.scrollTo() 方法
通过 window.scrollTo(x, y) 可以滚动到文档中的特定坐标位置。x 和 y 分别表示水平和垂直方向的像素值。
示例代码:
window.scrollTo(0, 500); // 滚动到垂直方向500像素的位置
支持平滑滚动选项:
window.scrollTo({
top: 500,
left: 0,
behavior: 'smooth'
});
使用 window.scrollBy() 方法window.scrollBy(x, y) 相对于当前位置滚动指定的距离。
示例代码:

window.scrollBy(0, 100); // 向下滚动100像素
平滑滚动版本:
window.scrollBy({
top: 100,
behavior: 'smooth'
});
使用 element.scrollIntoView() 方法
将特定元素滚动到视口中,支持对齐选项和平滑滚动。
示例代码:

document.getElementById('target').scrollIntoView({
behavior: 'smooth',
block: 'start' // 对齐到顶部
});
监听滚动事件
通过 window.addEventListener('scroll', callback) 监听页面滚动事件,实现自定义逻辑。
示例代码:
window.addEventListener('scroll', () => {
console.log(window.scrollY); // 获取当前垂直滚动位置
});
使用 CSS 属性 scroll-behavior
在 CSS 中设置 scroll-behavior: smooth 可以实现全局平滑滚动效果,无需额外 JavaScript 代码。
示例代码:
html {
scroll-behavior: smooth;
}
注意事项
- 平滑滚动 (
behavior: 'smooth') 可能在某些浏览器中不支持,需检查兼容性。 - 频繁触发滚动事件可能导致性能问题,建议使用防抖(debounce)或节流(throttle)优化。






