js 实现全屏滚动
全屏滚动实现方法
全屏滚动(Full Page Scroll)是一种常见的网页交互效果,用户滚动鼠标或触摸屏幕时,页面会以整屏为单位切换。以下是几种实现方法:
使用原生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) {
window.scrollTo({
top: sections[index].offsetTop,
behavior: 'smooth'
});
}
使用CSS Scroll Snap
CSS Scroll Snap可以更简单地实现全屏滚动效果,无需复杂JavaScript:
.container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
height: 100vh;
}
.section {
scroll-snap-align: start;
height: 100vh;
}
使用第三方库
对于更复杂的需求,可以使用专门的全屏滚动库:
-
fullPage.js - 功能丰富的全屏滚动库
new fullpage('#fullpage', { autoScrolling: true, scrollHorizontally: true }); -
Swiper.js - 支持全屏滚动的滑动库
new Swiper('.swiper-container', { direction: 'vertical', slidesPerView: 1, mousewheel: true, pagination: { el: '.swiper-pagination', clickable: true } });
移动端适配
针对触摸设备需要添加触摸事件处理:

let startY;
document.addEventListener('touchstart', (e) => {
startY = e.touches[0].clientY;
});
document.addEventListener('touchend', (e) => {
const endY = e.changedTouches[0].clientY;
if (startY - endY > 50) {
// 向上滑动
if (currentSection < totalSections - 1) {
currentSection++;
scrollToSection(currentSection);
}
} else if (endY - startY > 50) {
// 向下滑动
if (currentSection > 0) {
currentSection--;
scrollToSection(currentSection);
}
}
});
性能优化建议
- 使用
requestAnimationFrame优化滚动动画 - 避免在滚动过程中进行复杂的DOM操作
- 对滚动事件进行节流处理
- 考虑使用CSS硬件加速(transform属性)
以上方法可以根据项目需求选择适合的实现方式,简单的效果可以使用CSS Scroll Snap,复杂交互建议使用成熟的第三方库。






