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

如何实现点击图片显示对应隐藏文本的通用JS逻辑

实现方案

你不需要为每张图片单独编写点击函数,只要统一图片和对应说明文本的关联规则,绑定一次全局事件就能处理所有交互,完全避免重复代码。


第一步:统一关联规则

你可以直接沿用现有ID的命名规律:所有带b前缀ID的图片,对应去掉前缀后ID一致的说明块,比如id="bSOE"的图片对应id="SOE"的说明,后续新增图片只要遵守这个规则就不需要改JS逻辑。
如果觉得ID截取不够直观,也可以给图片元素加自定义data-target属性,直接写死对应说明块的ID,容错率更高。

第二步:调整HTML结构

把所有说明块按规则补全,同时去掉HTML标签上硬写的onclick属性,实现结构和逻辑分离:

<div class="mn_bo3">
  <div class="map" id="bSOE" style="background-image: url('source/Soe.png')"></div>
  <div class="map" id="bTG" style="background-image: url('source/tg.png')"></div>
  <div class="map" id="bDER" style="background-image: url('source/Der.png')"></div>
  <div class="map" id="bZNS" style="background-image: url('source/Zns.png')"></div>
  <div class="map" id="bGK" style="background-image: url('source/Gk.png')"></div>
</div>

<!-- 说明块ID和图片ID(去掉前缀b后)一一对应 -->
<div class="secret" id="SOE" style="display:none;">
  <p>Here are the list of the easter eggs of Shadow of Evil map :</p>
</div>
<div class="secret" id="TG" style="display:none;">
  <p>Here are the list of the easter eggs of The Giant map :</p>
</div>
<div class="secret" id="DER" style="display:none;">
  <p>Here are the list of the easter eggs of Der Eisendrache map :</p>
</div>
<div class="secret" id="ZNS" style="display:none;">
  <p>Here are the list of the easter eggs of Zetsubou No Shima map :</p>
</div>
<div class="secret" id="GK" style="display:none;">
  <p>Here are the list of the easter eggs of Gorod Krovi map :</p>
</div>

第三步:编写通用交互逻辑

只需要写一次事件绑定,自动处理所有图片的点击切换逻辑:

// 等页面DOM加载完成后再绑定事件,避免找不到元素
document.addEventListener('DOMContentLoaded', () => {
  const allMaps = document.querySelectorAll('.map');
  const allSecretTexts = document.querySelectorAll('.secret');

  allMaps.forEach(mapEl => {
    mapEl.addEventListener('click', () => {
      // 取当前点击图片对应的说明块ID:去掉ID开头的b前缀
      const targetId = mapEl.id.slice(1);
      const targetTextEl = document.getElementById(targetId);
      const isTargetShow = getComputedStyle(targetTextEl).display !== 'none';

      // 先隐藏所有说明块
      allSecretTexts.forEach(textEl => textEl.style.display = 'none');
      // 之前是显示状态就保持隐藏,否则显示当前对应说明
      if (!isTargetShow) {
        targetTextEl.style.display = 'block';
      }
    })
  })
})

可选优化

如果后续图片和说明的对应关系可能变复杂,把ID截取逻辑换成自定义属性读取即可,不需要改动核心交互逻辑:

  • 图片标签上加data-target属性:<div class="map" data-target="SOE" style="..."></div>
  • JS里把取targetId的代码改成const targetId = mapEl.dataset.target;
    这样就算ID命名没有规律也能正常匹配,灵活度更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 05:30:56