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

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数: fun…

js 实现图片轮播

js 实现图片轮播

基础实现方案 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS负责样式布局,JavaScript处理轮播逻辑。 <div class="…

js实现图片滚动

js实现图片滚动

图片滚动的实现方法 使用CSS动画实现 通过CSS的animation和@keyframes可以实现简单的图片滚动效果。这种方法适合静态图片的无缝循环滚动。 <style> .scr…

js验证码实现

js验证码实现

验证码的基本原理 验证码(CAPTCHA)用于区分人类用户和自动化程序。常见类型包括图形验证码、滑动验证码、短信验证码等。JavaScript 可用于前端验证码的生成和验证逻辑。 图形验证码实现 使…

js实现音乐播放

js实现音乐播放

使用HTML5 Audio API实现音乐播放 在JavaScript中,可以通过HTML5的Audio API轻松实现音乐播放功能。以下是基本实现方法: // 创建Audio对象 const au…