桌面端下拉Submenu显示正常,移动端/平板端Submenu无法显示问题求助
Let’s figure out why your submenu works flawlessly on desktop but vanishes on mobile and tablet. Here are the most likely issues and targeted fixes based on your code:
1. CSS Media Query Gaps
Desktop views probably use hover to reveal the submenu, but touch devices don’t support hover—so your mobile/tablet styles might be hiding the submenu by default without a way to toggle it.
First, audit your CSS for media queries targeting small screens. You might have something like this that’s blocking visibility:
/* Desktop: Show submenu on hover */ .menu-item-has-children:hover .sub-menu { display: block; } /* Mobile/Tablet: Submenu hidden by default (no toggle rule) */ @media (max-width: 768px) { .sub-menu { display: none; /* Ensure it doesn't get clipped by parent containers */ position: static; width: 100%; margin-top: 10px; } }
Add a toggle class to control visibility:
/* Trigger this class via JS when the button is clicked */ .sub-menu.active { display: block; }
2. Missing Touch-Friendly Interaction Logic
On mobile, you need a click handler for the .button_open span to show/hide the submenu (since hover doesn’t work). Here’s a simple vanilla JS snippet to add:
// Toggle submenu when the open button is clicked document.querySelectorAll('.button_open').forEach(button => { button.addEventListener('click', (e) => { e.preventDefault(); const subMenu = button.nextElementSibling; subMenu.classList.toggle('active'); // Optional: Add a visual state for the button button.classList.toggle('menu-open'); }); }); // Handle the BACK button in the submenu document.querySelectorAll('.menu-item.back a').forEach(backLink => { backLink.addEventListener('click', (e) => { e.preventDefault(); const subMenu = backLink.closest('.sub-menu'); subMenu.classList.remove('active'); }); });
3. Overflow or Positioning Conflicts
Mobile menus often use overflow: hidden on parent containers to manage scrolling, which can cut off the submenu. Check if any parent of .menu-item-has-children has overflow: hidden—if so, either remove that rule for mobile or switch the submenu’s position to static (instead of absolute) so it stays in the document flow.
Also, verify the submenu isn’t positioned outside the viewport on small screens. Adjust top, left, or transform values in your media queries if needed.
内容的提问来源于stack exchange,提问作者varun dhoni

