当前位置:首页 > JavaScript

js 实现全屏滚动

2026-03-01 04:59:19JavaScript

实现全屏滚动的 JavaScript 方法

全屏滚动效果可以通过监听鼠标滚轮事件或键盘事件,结合 CSS 和 JavaScript 实现。以下是两种常见的实现方式:

使用原生 JavaScript 实现

通过监听 wheel 事件,判断滚动方向并切换页面:

let currentSection = 0;
const sections = document.querySelectorAll('.fullscreen-section');

window.addEventListener('wheel', (e) => {
  if (e.deltaY > 0 && currentSection < sections.length - 1) {
    currentSection++;
  } else if (e.deltaY < 0 && currentSection > 0) {
    currentSection--;
  }

  sections[currentSection].scrollIntoView({
    behavior: 'smooth'
  });
});

对应的 HTML 结构:

<div class="fullscreen-section">Section 1</div>
<div class="fullscreen-section">Section 2</div>
<div class="fullscreen-section">Section 3</div>

CSS 样式:

js 实现全屏滚动

.fullscreen-section {
  height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
}

使用第三方库(如 fullPage.js)

fullPage.js 是一个流行的全屏滚动库,可以快速实现效果:

安装:

js 实现全屏滚动

npm install fullpage.js

使用:

import fullpage from 'fullpage.js';

new fullpage('#fullpage', {
  sectionsColor: ['#f2f2f2', '#4BBFC3', '#7BAABE'],
  navigation: true,
  scrollingSpeed: 1000
});

HTML 结构:

<div id="fullpage">
  <div class="section">Section 1</div>
  <div class="section">Section 2</div>
  <div class="section">Section 3</div>
</div>

注意事项

  • 移动端适配需要额外处理触摸事件。
  • 考虑禁用默认滚动行为以避免冲突。
  • 性能优化:节流滚动事件,避免快速滚动时多次触发。

兼容性处理

对于旧浏览器,可以添加 polyfill 或回退方案:

// 平滑滚动 polyfill
if (!('scrollBehavior' in document.documentElement.style)) {
  import('smoothscroll-polyfill').then(module => module.polyfill());
}

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

相关文章

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

vue实现全屏

vue实现全屏

Vue 实现全屏功能 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 来完成。以下是具体的实现方法: 使用 Fullscreen API 浏览器提供了 requestF…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含…

js实现求导

js实现求导

实现数值求导的方法 在JavaScript中实现求导通常采用数值方法,因为JavaScript不是符号计算语言。以下是常见的数值微分方法: 中心差分法 中心差分法提供较高精度的导数近似: fu…

js实现正交

js实现正交

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