js 实现全屏滚动
实现全屏滚动的 JavaScript 方法
全屏滚动是一种常见的网页交互效果,通常用于单页应用或展示型网站。以下是几种实现方式:
使用原生 JavaScript 实现
监听鼠标滚轮事件或触摸事件,通过计算滚动距离触发页面切换:
let currentSection = 0;
const sections = document.querySelectorAll('.section');
const totalSections = sections.length;
window.addEventListener('wheel', (e) => {
if (e.deltaY > 0) {
// 向下滚动
if (currentSection < totalSections - 1) {
currentSection++;
scrollToSection(currentSection);
}
} else {
// 向上滚动
if (currentSection > 0) {
currentSection--;
scrollToSection(currentSection);
}
}
});
function scrollToSection(index) {
sections[index].scrollIntoView({
behavior: 'smooth'
});
}
使用 CSS scroll-snap 属性
结合 CSS 的 scroll-snap 特性实现更流畅的效果:
.container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
height: 100vh;
}
.section {
scroll-snap-align: start;
height: 100vh;
}
使用第三方库
常见的全屏滚动库可以简化开发:
- fullPage.js
- pagePiling.js
- swiper.js
以 fullPage.js 为例:
new fullpage('#fullpage', {
sectionsColor: ['#f2f2f2', '#4BBFC3', '#7BAABE'],
navigation: true,
scrollingSpeed: 1000
});
移动端兼容处理
需要额外处理触摸事件:
let startY;
window.addEventListener('touchstart', (e) => {
startY = e.touches[0].clientY;
});
window.addEventListener('touchmove', (e) => {
const endY = e.touches[0].clientY;
if (endY < startY - 50) {
// 向上滑动
if (currentSection < totalSections - 1) {
currentSection++;
scrollToSection(currentSection);
}
} else if (endY > startY + 50) {
// 向下滑动
if (currentSection > 0) {
currentSection--;
scrollToSection(currentSection);
}
}
});
性能优化建议
- 使用 requestAnimationFrame 优化滚动动画
- 对滚动事件进行节流处理
- 预加载下一屏的内容
- 考虑使用 CSS transform 代替直接修改 scrollTop
注意事项
- 确保浏览器兼容性
- 处理好滚动边界情况
- 提供导航指示器
- 考虑无障碍访问需求
- 测试不同设备上的表现
以上方法可以根据项目需求选择适合的实现方案,原生实现灵活性高但开发成本较大,第三方库可以快速实现但可能有体积开销。







