侧边栏菜单active类切换异常:仅首个选项可触发切换问题排查
Hey there, I see the issue right away! Let's get your sidebar menu working properly across all items.
The Root Problem
Your current JavaScript uses document.querySelector('.side-menu') — this method only returns the first element that matches the selector. That's why only the "Beverages" menu item responds to clicks, while the rest don't have any click event attached to them.
The Solution
We need to target all .side-menu elements, bind click events to each one, and manage the active class so only the clicked item stays highlighted. Here's how to adjust your code:
Updated JavaScript Code
// Get all side-menu elements instead of just the first one const sideMenus = document.querySelectorAll('.side-menu'); const fbg = document.querySelector('.food-box-grid'); // Loop through each menu item to add click event sideMenus.forEach(menu => { menu.addEventListener('click', () => { // First, remove 'active' class from ALL side-menu items sideMenus.forEach(item => item.classList.remove('active')); // Add 'active' class to the clicked menu item menu.classList.add('active'); // Toggle the food-box-grid active class (keep your original behavior here) fbg.classList.toggle('active'); }); });
Quick CSS Adjustment (Important!)
Your pseudo-element (::after) uses position: absolute, which needs a positioned parent to work correctly. Add this to your CSS to make the highlight bar stay within the menu item:
.side-menu { position: relative; /* Ensures the absolute pseudo-element is contained here */ /* Keep your existing styles for .side-menu */ }
How This Works
querySelectorAll('.side-menu')grabs every menu item in the sidebar, not just the first.- We loop through each item and attach a click handler.
- When an item is clicked, we first remove the
activeclass from all menu items to make sure only one is highlighted at a time (this matches your "current selected item" requirement). - Then we add the
activeclass to the clicked item, which triggers your CSS highlight bar. - We keep the original toggle behavior for
.food-box-gridsince that's part of your existing logic.
Bonus: If You Want Toggle (Not Single Selection)
If you ever want to let users toggle individual items on/off instead of single selection, you can modify the click handler to just toggle the class on the clicked item (without removing from others):
menu.addEventListener('click', () => { menu.classList.toggle('active'); fbg.classList.toggle('active'); });
But based on your description (a "current selected item" indicator), the first solution (single selection) is what you need.
内容的提问来源于stack exchange,提问作者Kerbo6

