滚动过首屏后如何修改菜单及菜单背景样式
页面滚动过首屏后修改菜单背景样式的实现方案
核心逻辑:监听页面滚动事件,对比当前滚动距离和首屏视口高度,动态切换菜单的样式类
基础实现步骤
- 第一步:定义菜单的默认样式和滚动后的目标样式,建议加过渡动画提升交互流畅度
/* 菜单默认样式:固定在顶部,默认透明背景 */ .nav { position: fixed; top: 0; left: 0; width: 100%; z-index: 999; background: transparent; transition: all 0.3s ease; } /* 滚动过首屏后新增的样式类 */ .nav.scrolled { background: #ffffff; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); }
- 第二步:编写JS逻辑监听滚动事件,动态增删样式类
const navEl = document.querySelector('.nav'); // 首屏高度取当前视口高度即可 const firstScreenHeight = window.innerHeight; window.addEventListener('scroll', () => { if (window.scrollY > firstScreenHeight) { navEl.classList.add('scrolled'); } else { navEl.classList.remove('scrolled'); } });
性能优化建议
滚动事件触发频率极高,直接绑定逻辑会造成不必要的性能消耗,建议添加节流函数限制逻辑触发频率
// 简易节流函数,默认100ms触发一次 function throttle(fn, delay = 100) { let timer = null; return function(...args) { if (!timer) { timer = setTimeout(() => { fn.apply(this, args); timer = null; }, delay) } } } // 用节流函数包装滚动逻辑 window.addEventListener('scroll', throttle(() => { const navEl = document.querySelector('.nav'); navEl.classList.toggle('scrolled', window.scrollY > window.innerHeight); }));
常用框架简化实现
Vue3 示例
<script setup> import { ref, onMounted, onUnmounted } from 'vue' const isScrolled = ref(false) const handleScroll = throttle(() => { isScrolled.value = window.scrollY > window.innerHeight }, 100) onMounted(() => window.addEventListener('scroll', handleScroll)) onUnmounted(() => window.removeEventListener('scroll', handleScroll)) </script> <template> <div class="nav" :class="{ scrolled: isScrolled }">菜单内容</div> </template>
React 示例
import { useState, useEffect } from 'react' const Nav = () => { const [isScrolled, setIsScrolled] = useState(false) useEffect(() => { const handleScroll = throttle(() => { setIsScrolled(window.scrollY > window.innerHeight) }, 100) window.addEventListener('scroll', handleScroll) return () => window.removeEventListener('scroll', handleScroll) }, []) return <div className={`nav ${isScrolled ? 'scrolled' : ''}`}>菜单内容</div> }
内容的提问来源于stack exchange,提问作者Not Found
相关产品推荐
相关产品推荐

