You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

侧边栏菜单active类切换异常:仅首个选项可触发切换问题排查

Fixing Active Class Toggle for All Sidebar Menu Items

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

  1. querySelectorAll('.side-menu') grabs every menu item in the sidebar, not just the first.
  2. We loop through each item and attach a click handler.
  3. When an item is clicked, we first remove the active class from all menu items to make sure only one is highlighted at a time (this matches your "current selected item" requirement).
  4. Then we add the active class to the clicked item, which triggers your CSS highlight bar.
  5. We keep the original toggle behavior for .food-box-grid since 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:08:13