js实现页面滚动
监听滚动事件
使用 window.addEventListener 监听 scroll 事件,可以实时获取滚动位置:
window.addEventListener('scroll', function() {
console.log(window.scrollY); // 垂直滚动距离
console.log(window.scrollX); // 水平滚动距离
});
平滑滚动到指定位置
使用 window.scrollTo 方法实现平滑滚动,通过 behavior: 'smooth' 启用动画效果:
window.scrollTo({
top: 500, // 垂直目标位置
left: 0, // 水平目标位置
behavior: 'smooth'
});
滚动到页面顶部或底部
通过 window.scrollTo 结合 document.body.scrollHeight 实现:

// 滚动到顶部
window.scrollTo({ top: 0, behavior: 'smooth' });
// 滚动到底部
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth'
});
滚动到指定元素
使用 Element.scrollIntoView 方法将特定元素滚动到视口中:
document.getElementById('target-element').scrollIntoView({
behavior: 'smooth',
block: 'start' // 对齐方式:start/center/end
});
自定义滚动动画
通过 requestAnimationFrame 实现自定义滚动动画:

function smoothScrollTo(targetY, duration = 1000) {
const startY = window.scrollY;
const distance = targetY - startY;
const startTime = performance.now();
function step(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, startY + distance * progress);
if (progress < 1) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
// 调用示例
smoothScrollTo(800);
滚动节流优化
对滚动事件进行节流处理,避免性能问题:
let ticking = false;
window.addEventListener('scroll', function() {
if (!ticking) {
requestAnimationFrame(function() {
// 实际处理逻辑
console.log(window.scrollY);
ticking = false;
});
ticking = true;
}
});
滚动位置恢复
在页面刷新时恢复之前的滚动位置:
// 保存位置
window.addEventListener('beforeunload', () => {
sessionStorage.setItem('scrollPos', window.scrollY);
});
// 恢复位置
window.addEventListener('load', () => {
const scrollPos = sessionStorage.getItem('scrollPos');
if (scrollPos) {
window.scrollTo(0, parseInt(scrollPos));
}
});






