本文目录导读:

实现网页页面滚动,主要可以通过 JavaScript 或 CSS 两种方式,以下按使用场景分类,列出最常用的几种方法:
JavaScript 方法(最常用,支持控制位置和动画)
使用 scrollTo() —— 滚动到绝对坐标
// 滚动到页面顶部(x=0, y=0)
window.scrollTo(0, 0);
// 滚动到页面底部
window.scrollTo(0, document.body.scrollHeight);
// 平滑滚动(可选 behavior: 'smooth')
window.scrollTo({
top: 1000,
behavior: 'smooth' // 平滑滚动
});
使用 scrollBy() —— 相对当前位置滚动
// 向下滚动 300 像素
window.scrollBy(0, 300);
// 向上滚动 200 像素(负值)
window.scrollBy(0, -200);
// 平滑相对滚动
window.scrollBy({
top: 500,
behavior: 'smooth'
});
使用 scrollIntoView() —— 滚动到指定元素位置
// 获取目标元素
const element = document.getElementById('section2');
// 滚动到该元素可见
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
// block 可选: 'start', 'center', 'end', 'nearest'
使用 scrollTop 属性 —— 直接设置滚动位置
// 设置滚动条位置(垂直) window.scrollY; // 获取当前滚动位置 document.documentElement.scrollTop = 500; document.body.scrollTop = 500; // 兼容某些旧浏览器 // 水平滚动 window.scrollX; document.documentElement.scrollLeft = 200;
平滑滚动的通用函数(兼容旧浏览器)
function smoothScrollTo(targetY, duration = 500) {
const startY = window.scrollY;
const diff = targetY - startY;
const startTime = performance.now();
function step(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
// easeInOut 缓动函数
const ease = progress < 0.5
? 4 * progress * progress * progress
: 1 - Math.pow(-2 * progress + 2, 3) / 2;
window.scrollTo(0, startY + diff * ease);
if (progress < 1) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
// 使用
smoothScrollTo(2000);
CSS 方法(只在同一页面锚点跳转时有效)
全局平滑滚动(所有锚点跳转)
html {
scroll-behavior: smooth;
}
然后使用 #section2 链接即可平滑滚动。
指定元素滚动捕捉(适合整屏滚动效果)
.scroll-container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
height: 100vh;
}
.section {
scroll-snap-align: start;
height: 100vh;
}
特定元素内部的滚动(滚动容器)
如果页面内有一个可滚动的 div,需要操作它的滚动:
const container = document.querySelector('.scrollable-div');
// 设置内部滚动位置
container.scrollTop = 300;
// 或
container.scrollTo({ top: 500, behavior: 'smooth' });
// 或
container.scrollBy({ top: 100, behavior: 'smooth' });
常见场景示例
点击按钮滚动到页面顶部
document.querySelector('.back-to-top').addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
滚动加载更多(判断滚动到底部)
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
console.log('到达底部,加载更多内容...');
}
});
滚动动画(每隔一段时间自动滚动)
let currentPos = 0;
const interval = setInterval(() => {
currentPos += 300;
if (currentPos > document.body.scrollHeight) {
clearInterval(interval);
}
window.scrollTo({ top: currentPos, behavior: 'smooth' });
}, 2000);
注意事项
behavior: 'smooth'在 Safari 和某些旧浏览器中可能不支持,需用 JS 动画替代- 滚动性能:频繁滚动(如
scroll事件)建议加requestAnimationFrame或throttle节流 document.documentElementvsdocument.body:在怪异模式下可能不同,建议统一用window.scrollTo- 水平滚动:大多数方法都有水平和垂直两个方向,统一使用
{ left: x, top: y }
推荐用法:日常开发中,window.scrollTo({top: value, behavior: 'smooth'}) + element.scrollIntoView({behavior: 'smooth'}) 已经能满足 90% 的需求,如果需要精确控制动画曲线,再使用 requestAnimationFrame 自定义。