如何实现点击导航按钮时仅展开对应下拉导航栏?
解决导航栏下拉批量展开问题
你的核心问题在于toggleDropdown函数会遍历所有.dropdown元素切换show类,导致点击任意按钮都会触发所有下拉栏展开/收起。以下是修复方案:
修改后的JavaScript代码
const dropdownButtons = document.querySelectorAll(".dropdownButton"); function toggleDropdown(button) { // 定位当前按钮对应的下拉菜单 const dropdown = button.parentElement.querySelector(".dropdown"); // 切换下拉菜单的显示状态 dropdown.classList.toggle("show"); // 同步切换箭头旋转状态(可选优化) const arrow = button.querySelector("img"); arrow.classList.toggle("rotateImg"); } dropdownButtons.forEach((btn) => { btn.addEventListener("click", (e) => { // 使用currentTarget确保获取绑定事件的按钮(避免点击内部img时出错) toggleDropdown(e.currentTarget); }); });
关键修复点说明
- 精准定位目标下拉栏:不再全局操作所有
.dropdown元素,而是通过点击的按钮,找到它所在的.dropdownItem父元素下的对应下拉菜单,仅对该元素进行状态切换。 - 使用
currentTarget替代target:e.target会返回实际点击的元素(比如按钮内的箭头图片),而e.currentTarget始终指向绑定事件的按钮本身,避免因点击按钮内部元素导致的定位错误。 - 交互体验优化:同步处理箭头的旋转状态,让下拉展开/收起的交互更直观。
额外扩展(可选)
如果需要实现「点击页面其他区域收起所有下拉」或「同一时间仅展开一个下拉」的效果,可以添加以下代码:
// 点击页面非下拉区域时收起所有下拉 document.addEventListener("click", (e) => { if (!e.target.closest(".dropdownItem")) { document.querySelectorAll(".dropdown.show").forEach(dropdown => { dropdown.classList.remove("show"); }); document.querySelectorAll(".dropdownButton img.rotateImg").forEach(arrow => { arrow.classList.remove("rotateImg"); }); } }); // 同一时间仅展开一个下拉(点击新按钮时自动收起其他) dropdownButtons.forEach((btn) => { btn.addEventListener("click", (e) => { const currentButton = e.currentTarget; // 收起所有非当前按钮的下拉 dropdownButtons.forEach(otherBtn => { if (otherBtn !== currentButton) { const otherDropdown = otherBtn.parentElement.querySelector(".dropdown"); otherDropdown.classList.remove("show"); const otherArrow = otherBtn.querySelector("img"); otherArrow.classList.remove("rotateImg"); } }); // 切换当前下拉状态 toggleDropdown(currentButton); }); });
内容的提问来源于stack exchange,提问作者Codedede
相关产品推荐
相关产品推荐

