滚动触发背景切换动画改造:锁定页面至动画完成
滚动触发式背景与文本切换动画实现方案
核心需求实现步骤
- 初始页面锁定:加载时禁止页面滚动,仅响应用户滚动操作计数
- 滚动触发动画:累计用户几次滚动尝试后启动动画
- 动画完成解锁:动画结束后恢复页面滚动功能
1. CSS样式优化(替换内联样式)
将原JS中的内联样式转为CSS类,提升可维护性:
/* 页面锁定样式 */ body.locked { overflow: hidden; height: 100vh; } /* 自定义背景样式 */ .group1__bg.custom-bg { background: #1D1F23; background-image: url('../images/lines.svg'); background-repeat: no-repeat; background-size: cover; opacity: 1; transition: opacity 1s ease; animation: move-bg 15s linear infinite; } /* 文本淡入效果 */ h1.fade-in { color: #fff; animation: fadeIn 1s ease forwards; } /* 按钮淡出效果 */ .btn.fade-out { opacity: 0; transition: opacity 0.5s ease; pointer-events: none; } /* 侧边线条样式 */ .slide__lines.custom-lines { position: absolute; left: 10vw; right: 10vw; bottom: 0; top: 0; border-left: 1px solid #323544; border-right: 1px solid #323544; z-index: 1; } /* 关键帧动画定义 */ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes move-bg { from { background-position: 0 0; } to { background-position: 100% 0; } }
2. JavaScript逻辑改造(滚动触发+锁定控制)
替换原定时触发逻辑,改为滚动计数触发:
document.addEventListener('DOMContentLoaded', function() { // 获取DOM元素 const group1 = document.querySelector('.group1'); const group1Text = group1.querySelector('h1'); const group1Bg = group1.querySelector('.group1__bg'); const submitBtn = document.querySelector('.btn'); const slideLines = group1.querySelectorAll('.slide__lines'); // 滚动计数配置 let scrollCount = 0; const requiredScrolls = 2; // 触发动画所需的滚动次数 let isAnimationTriggered = false; // 初始锁定页面 document.body.classList.add('locked'); // 滚动事件处理函数 function handleScrollAttempt(e) { if (isAnimationTriggered) return; // 阻止默认滚动行为 e.preventDefault(); // 累计滚动次数 scrollCount++; // 达到触发条件,启动动画 if (scrollCount >= requiredScrolls) { startAnimationSequence(); } } // 动画执行序列 function startAnimationSequence() { isAnimationTriggered = true; // 移除滚动监听 document.removeEventListener('wheel', handleScrollAttempt, { passive: false }); // 执行动画逻辑 group1.classList.add('custom-color'); // 更新文本内容与样式 group1Text.textContent = "We help businesses grow through their automation. We accelerate the internal workflows of companies, increase efficiency, minimize routine tasks, and reduce costs."; group1Text.classList.add('fade-in'); // 背景过渡动画 group1Bg.style.opacity = '0'; setTimeout(() => { group1Bg.classList.add('custom-bg'); // 应用侧边线条样式 slideLines.forEach(line => line.classList.add('custom-lines')); // 隐藏提交按钮 submitBtn.classList.add('fade-out'); setTimeout(() => { submitBtn.style.display = 'none'; // 动画完全结束后解锁页面 setTimeout(() => { document.body.classList.remove('locked'); }, 1000); }, 500); }, 100); } // 监听滚轮事件(捕获用户滚动尝试) document.addEventListener('wheel', handleScrollAttempt, { passive: false }); });
关键实现说明
- 页面锁定:通过
body.locked类设置overflow:hidden和height:100vh,配合阻止wheel事件默认行为,确保用户无法滚动页面。 - 滚动计数:监听
wheel事件累计用户滚动尝试次数,达到设定值后触发动画。 - 动画解耦:将原内联样式转为CSS类,使样式与逻辑分离,便于后续维护。
- 解锁时机:在动画最后一个阶段完成后移除
locked类,确保动画完整展示后恢复滚动功能。
内容的提问来源于stack exchange,提问作者exfil
相关产品推荐
相关产品推荐

