如何实现点击仅展开一级子菜单?求纯JS/ES或jQuery解决方案
Got it, let's sort out this menu toggle issue! The problem with your original jQuery code is that it targets all <ul> elements inside the clicked <li>—not just the direct child. That's why clicking menu2 instantly expands both sub-menu2 and its nested items.
Here's a pure JavaScript (ES6+) solution that matches your desired behavior: only expand the direct child menu when clicking a parent, and let the sub-menu handle its own nested items when clicked.
Pure JS Implementation
const container = document.querySelector('.container'); container.addEventListener('click', (e) => { // Find the closest li that's part of our menu structure const targetLi = e.target.closest('.container > ul > li, .container > ul > li ul > li'); if (!targetLi) return; // Only target the DIRECT child ul of the clicked li const directSubMenu = targetLi.querySelector(':scope > ul'); if (!directSubMenu) return; // Toggle visibility with smooth animation (mimicking jQuery's toggle(200)) if (directSubMenu.style.display === 'none' || directSubMenu.style.display === '') { // Open the menu directSubMenu.style.display = 'block'; directSubMenu.style.height = directSubMenu.scrollHeight + 'px'; setTimeout(() => directSubMenu.style.height = 'auto', 200); } else { // Close the menu directSubMenu.style.height = directSubMenu.scrollHeight + 'px'; setTimeout(() => { directSubMenu.style.height = '0'; setTimeout(() => { directSubMenu.style.display = 'none'; directSubMenu.style.height = ''; }, 200); }, 10); } // Stop event bubbling so parent menus don't trigger when clicking children e.stopPropagation(); });
Updated CSS (For Smooth Animations)
We'll tweak the CSS to support the smooth expand/collapse animation:
div.container > ul ul { display: none; overflow: hidden; height: 0; transition: height 0.2s ease; }
Your Existing HTML Works As-Is
No changes needed here:
<div class="container"> <ul> <li>menu1 <ul> <li>testA</li> <li>testB</li> <li>testC</li> </ul> </li> <li>menu2 <ul> <li> sub-menu2 <ul> <li>issue1</li> <li>issue2</li> <li>issue3</li> </ul> </li> </ul> </li> </ul> </div>
Key Details
- Event Delegation: We attach one click listener to the container instead of individual lis—better performance, especially for larger menus.
:scopeSelector: Ensures we only target the direct child<ul>of the clicked<li>, not nested deeper ones.- Stop Propagation: Prevents clicks on sub-menus from triggering the parent menu's toggle action.
- Smooth Animation: Replaces jQuery's
toggle(200)with CSS transitions and dynamic height adjustments for a similar smooth effect.
内容的提问来源于stack exchange,提问作者Akash
相关产品推荐
相关产品推荐

