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

不同ID的多个div能否通过单个JavaScript函数分别控制?

多Div统一控制解决方案

问题本质

你当前的代码之所以只有最后一个div生效,是因为重复给window.onclick赋值——每次赋值都会覆盖之前绑定的函数,最终只有最后一次的函数会执行,自然只对window-three起作用。

实现单个函数控制所有Div

我们可以通过「统一类标识+批量元素处理」的方式,用单个函数完成需求,同时保留每个Div的唯一ID:

1. 给目标Div添加统一类

先给所有需要控制的Div加上同一个类(比如modal-box),这样能一次性选中所有目标元素:

<div id="window-one" class="container-one modal-box">1</div>
<div id="window-two" class="container-two modal-box">2</div>
<div id="window-three" class="container-three modal-box">3</div>

2. 编写单个处理函数

用querySelectorAll选中所有带统一类的元素,在window的点击事件里遍历判断并处理:

// 批量获取所有目标Div
const allModals = document.querySelectorAll('.modal-box');

// 绑定一次window点击事件
window.addEventListener('click', function(event) {
  allModals.forEach(modal => {
    // 原逻辑:点击Div本身时隐藏
    if (event.target === modal) {
      modal.style.display = 'none';
    }
  });
});

3. 适配「点击外部关闭」需求

如果你的实际需求是点击Div外部才关闭窗口(而非点击Div本身),可以调整判断逻辑:

window.addEventListener('click', function(event) {
  allModals.forEach(modal => {
    // 判断点击位置不在Div内,且Div当前处于显示状态
    if (!modal.contains(event.target) && modal.style.display !== 'none') {
      modal.style.display = 'none';
    }
  });
});

完整可运行代码

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      border: solid 2px black;
      height: 20px;
      background: yellow;
      margin: 5px;
    }
  </style>
</head>
<body>
  <div id="window-one" class="container-one modal-box">1</div>
  <div id="window-two" class="container-two modal-box">2</div>
  <div id="window-three" class="container-three modal-box">3</div>

  <script>
    const allModals = document.querySelectorAll('.modal-box');

    window.addEventListener('click', function(event) {
      allModals.forEach(modal => {
        if (event.target === modal) {
          modal.style.display = 'none';
        }
      });
    });
  </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:30:43