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

如何实现多个div的互斥显示/隐藏功能?

实现单Div独占显示的修改方案

核心思路

  1. 替换三个独立函数为一个通用函数,通过传入目标Div的ID复用逻辑,减少代码冗余
  2. 每次触发按钮时,先隐藏所有Div元素,再判断目标Div的当前状态:如果原本是隐藏则显示,否则保持隐藏(支持点击同一按钮关闭Div)

修改后的完整代码

JavaScript

function toggleDiv(targetId) {
  // 获取所有需要控制的Div元素
  const allDivs = document.querySelectorAll('.div');
  // 获取目标Div
  const targetDiv = document.getElementById(targetId);
  // 先隐藏所有Div
  allDivs.forEach(div => {
    div.style.display = 'none';
  });
  // 如果目标Div原本处于隐藏状态,则显示它;否则保持隐藏
  if (targetDiv.style.display === 'none') {
    targetDiv.style.display = 'block';
  }
}

CSS(保持原代码不变)

.div {
  width: 270px;
  height: 30px;
  padding-left: 10px;
}

HTML(修改按钮的onclick调用)

<button type="button" onclick="toggleDiv('Div_1')">Div 1 - Red</button>
<button type="button" onclick="toggleDiv('Div_2')" style="margin-left: 4px">Div 2 - Blue</button>
<button type="button" onclick="toggleDiv('Div_3')" style="margin-left: 4px">Div 3 - Green</button>
<div id="Div_1" class="div" style="background-color:red; display: none;"></div>
<div id="Div_2" class="div" style="background-color:blue; display: none;"></div>
<div id="Div_3" class="div" style="background-color:green; display: none;"></div>

可选优化方案

如果想让代码更易维护,推荐用CSS类控制显示状态,替代直接操作内联样式:

  1. 修改CSS:
.div {
  width: 270px;
  height: 30px;
  padding-left: 10px;
  display: none; /* 默认隐藏 */
}
.div.show {
  display: block;
}
  1. 修改JavaScript:
function toggleDiv(targetId) {
  const allDivs = document.querySelectorAll('.div');
  const targetDiv = document.getElementById(targetId);
  // 移除所有Div的显示类
  allDivs.forEach(div => div.classList.remove('show'));
  // 切换目标Div的显示状态
  if (!targetDiv.classList.contains('show')) {
    targetDiv.classList.add('show');
  }
}
  1. 简化HTML(移除内联的display: none):
<button type="button" onclick="toggleDiv('Div_1')">Div 1 - Red</button>
<button type="button" onclick="toggleDiv('Div_2')" style="margin-left: 4px">Div 2 - Blue</button>
<button type="button" onclick="toggleDiv('Div_3')" style="margin-left: 4px">Div 3 - Green</button>
<div id="Div_1" class="div" style="background-color:red;"></div>
<div id="Div_2" class="div" style="background-color:blue;"></div>
<div id="Div_3" class="div" style="background-color:green;"></div>

内容的提问来源于stack exchange,提问作者Nam Tab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:15:33