基于fullpage.js实现滚动时随机切换明暗主题SVG Logo
解决方案:滚动时随机切换对应主题的SVG Logo
嘿,这需求挺有意思的!结合fullpage.js的滚动事件,我们可以轻松实现每次切换区块时,根据区块的明暗主题随机替换Logo。下面是完整的实现步骤和代码:
核心思路
- 利用fullpage.js的
afterLoad回调,在每次滚动到新的全屏区块后触发逻辑 - 判断当前区块的主题(
.light或.dark) - 根据主题随机生成对应系列的SVG Logo路径,更新图片的
src属性 - 页面初始化时,先给第一个区块设置对应的初始随机Logo
完整代码实现
HTML(保留你的原有结构)
<nav> <a id="logo" href="#"> <img id="moody-logo" src="" alt="主题Logo"> </a> </nav> <!-- 你的fullpage.js区块结构示例 --> <div id="fullpage"> <div class="row dark">区块1(深色主题)</div> <div class="row light">区块2(浅色主题)</div> <div class="row dark">区块3(深色主题)</div> <!-- 更多区块... --> </div>
JavaScript 代码
// 初始化fullpage.js时配置回调 new fullpage('#fullpage', { // 其他fullpage配置项(比如导航、滚动速度等)可以加在这里 afterLoad: function(origin, destination, direction) { // 获取当前滚动到的区块DOM元素 const currentSection = destination.item; // 调用函数更新Logo updateThemeLogo(currentSection); } }); // 定义Logo的基础配置:总数量和不同主题的前缀 const LOGO_TOTAL = 6; const LOGO_PREFIX = { dark: 'dark_logo_', light: 'light_logo_' }; // 根据区块主题更新Logo的核心函数 function updateThemeLogo(sectionElement) { const logoImg = document.getElementById('moody-logo'); let logoPrefix; // 判断当前区块的主题类 if (sectionElement.classList.contains('dark')) { logoPrefix = LOGO_PREFIX.dark; } else if (sectionElement.classList.contains('light')) { logoPrefix = LOGO_PREFIX.light; } else { // 兜底逻辑:如果区块没有设置主题类,默认用dark系列 logoPrefix = LOGO_PREFIX.dark; console.warn('当前区块未设置light/dark主题类,默认使用dark Logo'); } // 生成1到6之间的随机整数(对应6组Logo) const randomNum = Math.floor(Math.random() * LOGO_TOTAL) + 1; // 拼接完整的Logo路径(如果Logo存放在特定文件夹,记得加路径前缀,比如./assets/) const logoSrc = `${logoPrefix}${randomNum}.svg`; // 更新图片的src属性 logoImg.src = logoSrc; } // 页面加载完成后,初始化第一个区块的Logo document.addEventListener('DOMContentLoaded', function() { const firstSection = document.querySelector('.row'); if (firstSection) { updateThemeLogo(firstSection); } });
关键细节说明
- fullpage.js回调时机:选择
afterLoad是因为它在滚动动画完成、区块完全加载后触发,能确保我们准确获取当前区块的类名 - 随机数生成:
Math.floor(Math.random() * LOGO_TOTAL) + 1确保生成1到6的整数,正好匹配你的6组Logo命名规则 - 主题判断:通过
classList.contains检查区块的类,逻辑简单直接,兼容性也好 - 初始化处理:页面加载时主动调用一次函数,避免初始状态下Logo为空的尴尬
如果你的SVG Logo存放在特定文件夹里,记得在logoSrc里加上路径前缀,比如./assets/logos/${logoPrefix}${randomNum}.svg。
内容的提问来源于stack exchange,提问作者Matija Ljevar
相关产品推荐
相关产品推荐

