实现滚动激活点击同款函数及多区块样式动态调整需求
实现方案
1. 统一处理Active类切换(点击+滚动触发)
把原有点击事件里的active类逻辑抽成独立函数,让点击和滚动操作都能复用,避免重复代码:
// 抽离active类切换核心逻辑 function activateSection(targetSection) { // 移除所有导航项的active状态 $('.nav-item').removeClass('active'); // 给对应导航项添加active类 $('.nav-item[href="#' + targetSection.attr('id') + '"]').addClass('active'); // 处理背景下移与section背景色 const sectionIndex = targetSection.index('section'); // 灯塔背景随section下移(每个section占100vh高度) $('.lighthouse-bg').css('transform', `translateY(${sectionIndex * 100}vh)`); // 给当前section设置对应背景色(可根据需求调整颜色数组) const sectionColors = ['#ffffff', '#f8f9fa', '#e9ecef', '#dee2e6']; targetSection.css('background-color', sectionColors[sectionIndex]); } // 原有点击事件逻辑 $('.nav-item').click(function(e) { e.preventDefault(); const targetSection = $($(this).attr('href')); activateSection(targetSection); // 可选:平滑滚动到目标区块 $('html, body').animate({ scrollTop: targetSection.offset().top }, 500); }); // 滚动监听触发active类切换 $(window).scroll(function() { const viewportMid = $(window).scrollTop() + $(window).height() / 2; $('section').each(function() { const sectionTop = $(this).offset().top; const sectionBottom = sectionTop + $(this).outerHeight(); // 视口中间位置落在当前section内时,激活该区块 if (viewportMid >= sectionTop && viewportMid < sectionBottom) { activateSection($(this)); return false; // 找到目标后终止遍历,提升性能 } }); });
2. 灯塔背景全屏与滚动跟随的CSS设置
设置背景容器为全屏固定定位,添加过渡动画保证下移效果平滑:
/* 灯塔背景容器 */ .lighthouse-bg { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; /* 强制全屏高度 */ background-image: url('你的灯塔背景图路径'); background-size: cover; background-position: center; z-index: -1; /* 放在内容下方 */ transition: transform 0.5s ease; /* 平滑过渡动画 */ } /* 每个section设置为全屏高度 */ section { height: 100vh; position: relative; z-index: 1; /* 保证内容在背景上方 */ padding: 2rem; box-sizing: border-box; /* 避免内边距撑高容器 */ }
3. 自定义Section背景色的两种方式
- 方式1:JS动态设置(已在
activateSection函数中实现),适合需要动态调整颜色的场景 - 方式2:CSS类切换,适合固定颜色的场景:
然后修改.section-1 { background-color: #ffffff; } .section-2 { background-color: #f8f9fa; } .section-3 { background-color: #e9ecef; } .section-4 { background-color: #dee2e6; }activateSection函数中的背景色部分:// 移除所有section的背景色类 $('section').removeClass('section-1 section-2 section-3 section-4'); // 给当前section添加对应类 targetSection.addClass(`section-${sectionIndex + 1}`);
内容的提问来源于stack exchange,提问作者Pierre
相关产品推荐
相关产品推荐

