当前位置:首页 > JavaScript

js 实现全屏滚动

2026-01-30 13:55:08JavaScript

实现全屏滚动的 JavaScript 方法

全屏滚动是一种常见的网页交互效果,通常用于单页应用或展示型网站。以下是几种实现方式:

使用原生 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) {
    sections[index].scrollIntoView({
        behavior: 'smooth'
    });
}

使用 CSS scroll-snap 属性

结合 CSS 的 scroll-snap 特性实现更流畅的效果:

.container {
    scroll-snap-type: y mandatory;
    overflow-y: scroll;
    height: 100vh;
}

.section {
    scroll-snap-align: start;
    height: 100vh;
}

使用第三方库

常见的全屏滚动库可以简化开发:

  • fullPage.js
  • pagePiling.js
  • swiper.js

以 fullPage.js 为例:

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

移动端兼容处理

需要额外处理触摸事件:

let startY;
window.addEventListener('touchstart', (e) => {
    startY = e.touches[0].clientY;
});

window.addEventListener('touchmove', (e) => {
    const endY = e.touches[0].clientY;
    if (endY < startY - 50) {
        // 向上滑动
        if (currentSection < totalSections - 1) {
            currentSection++;
            scrollToSection(currentSection);
        }
    } else if (endY > startY + 50) {
        // 向下滑动
        if (currentSection > 0) {
            currentSection--;
            scrollToSection(currentSection);
        }
    }
});

性能优化建议

  • 使用 requestAnimationFrame 优化滚动动画
  • 对滚动事件进行节流处理
  • 预加载下一屏的内容
  • 考虑使用 CSS transform 代替直接修改 scrollTop

注意事项

  • 确保浏览器兼容性
  • 处理好滚动边界情况
  • 提供导航指示器
  • 考虑无障碍访问需求
  • 测试不同设备上的表现

以上方法可以根据项目需求选择适合的实现方案,原生实现灵活性高但开发成本较大,第三方库可以快速实现但可能有体积开销。

js 实现全屏滚动

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

相关文章

vue实现全屏

vue实现全屏

Vue 实现全屏功能的方法 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 来实现。以下是几种常见的实现方式: 使用原生 Fullscreen API 通过调用 do…

js实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const ch…

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.…

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的H…

js实现计算器

js实现计算器

实现基础计算器功能 使用JavaScript创建一个基础计算器需要处理数字输入、运算符逻辑和结果显示。以下是一个简单的实现示例: let currentInput = '0'; let previo…

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…