实现单div打开时自动关闭其他div的原生JavaScript方案
Solution with Vanilla JavaScript
Got it, let's adjust your code to make sure only one description panel is open at a time—no jQuery needed! Here's how to do it step by step:
1. Update Your HTML
First, add a shared class (like team-description) to all your description divs. This makes it easy to select all of them with vanilla JS:
<!-- Example HTML structure --> <div class="row_team_pic"> <button onclick="openDescription('desc1')">Open Description 1</button> <div id="desc1" class="team-description">Description 1 content goes here</div> </div> <div class="row_team_pic"> <button onclick="openDescription('desc2')">Open Description 2</button> <div id="desc2" class="team-description">Description 2 content goes here</div> </div>
2. Rewrite the JavaScript Function
Modify your openDescription function to first close all other description panels before toggling the target one. We'll also fix the display check to account for CSS-set styles (not just inline ones):
function openDescription(description_id) { // Grab all description panels using the shared class const allDescriptions = document.querySelectorAll('.team-description'); const targetPanel = document.getElementById(description_id); // Close every panel except the clicked one allDescriptions.forEach(panel => { if (panel !== targetPanel) { panel.style.display = 'none'; } }); // Toggle the target panel's visibility (handles both inline and CSS-set styles) const currentDisplay = window.getComputedStyle(targetPanel).display; targetPanel.style.display = currentDisplay === 'block' ? 'none' : 'block'; }
3. Adjust Your CSS
You can keep your existing CSS, but add a rule to hide all description panels by default (instead of relying on inline styles):
.team-description { display: none; /* Hide all panels initially */ } .row_team_pic{ text-align:center; margin: -72px 0 15px; /* Shorthand for cleaner margin values */ } .container{ background-color:silver; width:150px; display: inline-block; /* Finished your incomplete display property */ }
How It Works
- We use
document.querySelectorAll('.team-description')to fetch all description panels in one go. - We loop through every panel and close any that aren't the one the user clicked on.
window.getComputedStyle()checks the actual display state of the target panel (this works even if visibility is set via CSS, not just inlinestyleattributes).- Finally, we toggle the target panel's visibility—if it was open, we close it; if closed, we open it (while keeping all others shut).
内容的提问来源于stack exchange,提问作者Cubesloth
相关产品推荐
相关产品推荐

