点击按钮时如何切换多个下拉菜单按钮的激活状态
Alright, let's break down what's going wrong here and fix it step by step. Your core problem is that when you click a new dropdown button, the old active button doesn't reset to its inactive state—and your original code had the state-switching logic commented out, which made things worse.
Here's the Fixed JavaScript Code
$(document).ready(function(e){ // Initialize all buttons to inactive state (button_right + collapsed) $('.btn.button_right').addClass('collapsed'); $('.btn.button_right').click(function(){ const currentBtn = $(this); const targetPanel = $(currentBtn.attr('href')); const otherBtns = $('.btn.button_right').not(currentBtn); // 1. Reset all other buttons to inactive state otherBtns.each(function(){ const $btn = $(this); // Switch back to inactive styling $btn.removeClass('button_down').addClass('button_right collapsed'); // Expand their corresponding dropdown content $($btn.attr('href')).collapse('show'); }); // 2. Toggle current button's state and its dropdown content currentBtn.toggleClass('collapsed'); if(currentBtn.hasClass('collapsed')){ // Activate button + collapse content currentBtn.removeClass('button_right').addClass('button_down'); targetPanel.collapse('hide'); } else { // Deactivate button + expand content currentBtn.removeClass('button_down').addClass('button_right'); targetPanel.collapse('show'); } }); });
Key Fixes Explained
- Resetting Other Buttons: When you click a button, we first grab all other dropdown buttons, switch them back to their inactive
button_rightstyle, and force their dropdowns to expand. This ensures the old active button doesn't stay stuck in an active state. - Restoring State Switch Logic: I uncommented and cleaned up your original state-checking code to properly toggle the button's active/inactive state based on the
collapsedclass. This syncs the button's appearance with whether its dropdown is hidden or shown. - Targeting the Right Panel: We use the button's
hrefattribute to directly target its corresponding dropdown panel, so we don't accidentally mess with other panels.
What You'll See Now
- Initial State: All buttons are inactive (
button_right), all dropdowns are collapsed. - Click Button A: A becomes active (
button_down), its dropdown collapses; any other buttons stay inactive with their dropdowns expanded. - Click Button B: B becomes active, its dropdown collapses; A automatically switches back to inactive, and its dropdown expands.
- Click A Again: A switches back to inactive, its dropdown expands; B stays active with its dropdown collapsed.
This matches exactly the behavior you're looking for!
内容的提问来源于stack exchange,提问作者Xandru
相关产品推荐
相关产品推荐

