如何关联菜单与区块:为对应section添加show类(HTML/CSS/JS)
实现菜单项与对应Section的联动显示功能
你已经完成了菜单项的active类切换逻辑,现在只需在现有代码基础上添加Section的show类切换逻辑即可,具体修改如下:
完整修改后的JavaScript代码
const allNavItem = document.querySelectorAll('.nav-item') // 新增:获取所有section元素 const allSections = document.querySelectorAll('.section') function removeActiveMenu() { allNavItem.forEach(item => { item.classList.remove('active') }) } // 新增:移除所有section的show类 function removeShowSection() { allSections.forEach(section => { section.classList.remove('show') }) } allNavItem.forEach(item => { item.addEventListener('click', (e) => { // 阻止默认锚点跳转行为(可选,按需启用) e.preventDefault() removeActiveMenu() item.classList.add('active') // 新增:处理section的show类切换 removeShowSection() // 从菜单项href中提取目标section的id(去掉开头的#) const targetSectionId = item.getAttribute('href').slice(1) // 找到对应section并添加show类 document.getElementById(targetSectionId).classList.add('show') }) })
修改说明
- 先获取所有带
.section类的元素,用于后续批量操作 - 新增
removeShowSection函数,确保每次只有一个section处于显示状态 - 在点击事件中:
- 可选调用
e.preventDefault()阻止浏览器默认锚点滚动行为 - 先清除所有section的
show类,再为目标section添加该类 - 通过菜单项的
href属性精准匹配对应section的ID
- 可选调用
原HTML代码无需修改
<nav class="nav-desktop"> <div class="nav-items"> <a class="nav-item" href="#about">About</a> <a class="nav-item" href="#ourteam">Skills</a> <a class="nav-item" href="#contact">Contact</a> </div> </nav> <section class="about section show" id="about"></section> <section class="ourteam section" id="ourteam"></section> <section class="contact section" id="contact"></section>
内容的提问来源于stack exchange,提问作者GaryNJ
相关产品推荐
相关产品推荐

