You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何关联菜单与区块:为对应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处于显示状态
  • 在点击事件中:
    1. 可选调用e.preventDefault()阻止浏览器默认锚点滚动行为
    2. 先清除所有section的show类,再为目标section添加该类
    3. 通过菜单项的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 07:16:29