当前位置:首页 > 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实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现tab选项卡切换

js实现tab选项卡切换

实现Tab选项卡切换的JavaScript方法 使用纯JavaScript实现Tab切换功能,可以通过监听点击事件动态切换内容显示状态。以下是两种常见实现方式: 基础DOM操作实现 // 获取所有…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现游标

js实现游标

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

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…

js实现上传文件

js实现上传文件

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。 <input type="file"…