点击按钮隐藏导航栏其余按钮的实现方法咨询
解决方案
问题分析
当前代码存在两个核心问题:
- 汉堡菜单切换的类名与CSS匹配不一致(JS用
activate,CSS用active) - 缺少点击按钮后隐藏其余按钮的样式与逻辑
修改后的代码
HTML(无需修改)
<div class="selectSection"> <button type="button" data-number="1" class="active">1</button> <button type="button" data-number="2">2</button> <button type="button" data-number="3">3</button> </div> <div class="hamburger"> <div class="line"></div> <div class="line"></div> <div class="line"></div> </div> <div> <div class="content" data-number="1"> <p>1st page</p> </div> <div class="content" data-number="2"> <p>2nd page</p> </div> <div class="content" data-number="3"> <p>3rd page</p> </div> </div>
CSS(补充移动端按钮隐藏样式)
.content:not(:first-child) { display: none; } .active { color: orange !important; } .hamburger { display: none; } @media all and (max-width: 800px) { .hamburger { display: inline-block; cursor: pointer; z-index: 7; } .hamburger .line { width: 30px; height: 3px; background: black; margin: 6px 0px; } .selectSection { display: none; overflow: hidden; } .selectSection.active { display: block; } /* 新增:折叠状态下仅显示激活按钮 */ .selectSection.collapsed button:not(.active) { display: none; } }
JS(修复类名+添加折叠逻辑)
// 切换激活状态、对应内容显示隐藏 const buttons = document.querySelectorAll(".selectSection button"); const selectSection = document.querySelector(".selectSection"); for (let button of buttons) { button.addEventListener("click", (e) => { const activeBtn = document.querySelector(".selectSection button.active"); if (activeBtn) { activeBtn.classList.remove("active"); } e.target.classList.add("active"); // 切换内容显示 const allContent = document.querySelectorAll(".content"); for (let content of allContent) { if (content.getAttribute("data-number") === button.getAttribute("data-number")) { content.style.display = "block"; } else { content.style.display = "none"; } } // 移动端点击按钮后折叠菜单,仅保留当前按钮 if (window.innerWidth <= 800) { selectSection.classList.add("collapsed"); } }); } // 汉堡菜单逻辑 const hamburger = document.querySelector(".hamburger"); hamburger.onclick = function () { selectSection.classList.toggle("active"); // 打开菜单时移除折叠状态,显示所有按钮 selectSection.classList.remove("collapsed"); };
关键修改点
- 修复汉堡菜单类名:将JS中
toggle("activate")改为toggle("active"),与CSS选择器匹配 - 添加折叠状态样式:在媒体查询中新增
.selectSection.collapsed button:not(.active)规则,隐藏非激活按钮 - 按钮点击逻辑扩展:点击按钮时给
selectSection添加collapsed类,移动端触发折叠 - 汉堡菜单逻辑优化:点击汉堡菜单时移除
collapsed类,确保再次打开时显示所有按钮
内容的提问来源于stack exchange,提问作者fakermaker
相关产品推荐
相关产品推荐

