js 实现滚屏
实现滚屏的几种方法
使用 window.scrollTo()
window.scrollTo() 方法可以滚动到文档中的特定坐标位置。可以设置平滑滚动效果。
// 滚动到指定位置(x, y)
window.scrollTo({
top: 1000,
behavior: 'smooth'
});
使用 window.scrollBy()
window.scrollBy() 方法可以相对于当前位置滚动指定的距离。
// 向下滚动 500 像素
window.scrollBy({
top: 500,
behavior: 'smooth'
});
使用 Element.scrollIntoView()
Element.scrollIntoView() 方法可以让元素滚动到可视区域。
// 获取目标元素
const element = document.getElementById('target');
// 滚动到元素位置
element.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
使用 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);
const ease = progress < 0.5
? 2 * progress * progress
: 1 - Math.pow(-2 * progress + 2, 2) / 2;
window.scrollTo(0, startY + distance * ease);
if (timeElapsed < duration) requestAnimationFrame(animation);
}
requestAnimationFrame(animation);
}
// 使用示例
smoothScrollTo(1000, 1000);
监听滚动事件
可以通过监听 scroll 事件实现滚动时的交互效果。
window.addEventListener('scroll', function() {
console.log('当前滚动位置:', window.pageYOffset);
});
使用第三方库
如果项目复杂度较高,可以考虑使用第三方库如 smooth-scroll 或 scrollreveal。
// 使用 smooth-scroll 示例
import SmoothScroll from 'smooth-scroll';
const scroll = new SmoothScroll('a[href*="#"]', {
speed: 800,
easing: 'easeInOutCubic'
});
注意事项
- 平滑滚动 (
behavior: 'smooth') 在部分旧浏览器中可能不支持,需要添加 polyfill。 - 自定义动画时注意性能优化,避免频繁触发重排和重绘。
- 移动端滚动行为可能与桌面端不同,需进行兼容性测试。
以上方法可以根据具体需求选择使用,简单场景推荐使用原生 API,复杂动画建议使用第三方库。







