当前位置:首页 > JavaScript

js 实现全屏滚动

2026-04-04 05:36:04JavaScript

全屏滚动实现方法

全屏滚动(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;
}

使用第三方库

对于更复杂的需求,可以使用专门的全屏滚动库:

  1. fullPage.js - 功能丰富的全屏滚动库

    new fullpage('#fullpage', {
      autoScrolling: true,
      scrollHorizontally: true
    });
  2. Swiper.js - 支持全屏滚动的滑动库

    new Swiper('.swiper-container', {
      direction: 'vertical',
      slidesPerView: 1,
      mousewheel: true,
      pagination: {
        el: '.swiper-pagination',
        clickable: true
      }
    });

移动端适配

针对触摸设备需要添加触摸事件处理:

js 实现全屏滚动

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,复杂交互建议使用成熟的第三方库。

标签: 全屏js
分享给朋友:

相关文章

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

原生js实现轮播图

原生js实现轮播图

基本结构搭建 HTML部分需要包含轮播图容器、图片列表及导航按钮。结构示例如下: <div class="slider-container"> <div class="slid…

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: functio…