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

实现单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 inline style attributes).
  • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:34:22