嵌套下拉菜单同时展开问题及动态交互需求技术咨询
Got it, let's break down why all your sub-menus are opening together and fix it step by step.
The Root Problem
Your current jQuery code targets every .sub-menu on the page when any .dropdown-toggle is clicked. That's why clicking one "+" opens all sub-menus at once. We need to target only the sub-menu directly linked to the clicked toggle button.
Step 1: Fix the jQuery Logic
Replace your existing jQuery code with this. It uses event delegation (so it works for dynamically added WordPress menus) and only toggles the sub-menu tied to the clicked button:
$(document).on('click', '.dropdown-toggle', function(e) { e.preventDefault(); // Get the parent menu item and its direct sub-menu const $toggleBtn = $(this); const $parentLi = $toggleBtn.closest('.menu-item-has-children'); const $targetSubMenu = $parentLi.children('.sub-menu'); // Toggle the sub-menu visibility $targetSubMenu.toggleClass('toggle-on'); // Update the toggle symbol (+/-) and aria attribute for accessibility const isExpanded = $targetSubMenu.hasClass('toggle-on'); $toggleBtn.attr('aria-expanded', isExpanded); $toggleBtn.find('.dropdown-symbol').text(isExpanded ? '-' : '+'); });
Step 2: Update CSS for Hover & Toggle Compatibility
Modify your CSS to support both hover and click interactions, and ensure styles only apply to the relevant sub-menu:
/* Base sub-menu hidden state */ .main-navigation .sub-menu { display: none; /* Optional: Add transition for smooth show/hide */ transition: all 0.3s ease; } /* Show sub-menu when toggled OR parent menu item is hovered */ .main-navigation .sub-menu.toggle-on, .main-navigation .menu-item-has-children:hover > .sub-menu { display: block; } /* Keep your existing core styles */ .main-navigation ul, .main-navigation ul ul, .main-navigation ul ul ul { list-style: none; } .main-navigation ul li a { color: #fff; text-decoration: none; } .main-navigation ul { display: flex; justify-content: flex-end; align-items: center; } .main-navigation ul li { margin-right: 2rem; /* Optional: Position sub-menus properly */ position: relative; } /* Optional: Style sub-menus to avoid layout shifts */ .main-navigation .sub-menu { position: absolute; top: 100%; left: 0; background-color: #222; padding: 1rem; min-width: 200px; }
Step 3: Verify Dynamic WordPress Menu Support
Since we used $(document).on('click', '.dropdown-toggle', ...) instead of directly binding to existing elements, any new sub-menus you add in WordPress will automatically work with the click/toggle functionality—no extra code needed.
Key Improvements
- Targeted Toggling: Only the sub-menu under the clicked button opens/closes
- Accessibility: Updates
aria-expandedattribute and toggle symbol for screen readers - Dynamic Compatibility: Works with new menus added via WordPress admin
- Hover Support: Sub-menus also show when hovering over parent items, as requested
内容的提问来源于stack exchange,提问作者billy

