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

双翻转卡片(Flip Card)隐藏/显示(Hide/Show)按钮异常:第二个按钮点击无响应的解决方法

修复翻转卡片的Hide/Show按钮失效问题

嘿,我明白你遇到的麻烦了——问题出在重复使用了相同的ID(button和newpost)!在HTML规则里,ID是页面唯一的标识,document.getElementById()只会返回第一个匹配该ID的元素,所以第二个卡片的按钮根本没绑定到正确的点击事件,甚至会误触发第一个卡片的内容显示/隐藏。

下面是具体的修复方案:

步骤1:替换重复ID为类名

把两个卡片里的id='button'改成class='toggle-button',id='newpost'改成class='toggle-content'。类名可以在多个元素上重复使用,不会产生冲突。

步骤2:修改JS脚本,绑定每个按钮的独立事件

用querySelectorAll获取所有切换按钮,然后遍历每个按钮,通过DOM相对查找找到当前按钮对应的内容块,这样每个按钮只会控制自己卡片里的内容,不会影响其他卡片。

修改后的完整代码

HTML部分

<div id="main">
  <div name="first flip card" style="margin-left: 50px;">
    <label>
      <input type="checkbox" />
      <div class="flip-card">
        <div class="front">
          <h1>Գերմանիա</h1>
          <p style="font-size: 50px;">1</p>
        </div>
        <div class="back">
          <h1>About me</h1>
          <hr />
          <p>some text</p>
          <button class='toggle-button'>hide/show</button>
          <p class="toggle-content" style="display: none;"> Test text</p>
          <hr />
        </div>
      </div>
    </label>
  </div>
  <div name="second flip card" style="margin-left: 50px;">
    <label>
      <input type="checkbox" />
      <div class="flip-card">
        <div class="front">
          <h1>Գերմանիա</h1>
          <p style="font-size: 50px;">1</p>
        </div>
        <div class="back">
          <h1>About me</h1>
          <hr />
          <p>some text</p>
          <button class='toggle-button'>hide/show</button>
          <p class="toggle-content" style="display: none;"> Test text</p>
          <hr />
        </div>
      </div>
    </label>
  </div>
</div>

JS部分

// 获取所有切换按钮
const buttons = document.querySelectorAll('.toggle-button');

// 遍历每个按钮,绑定点击事件
buttons.forEach(button => {
  button.onclick = function() {
    // 找到当前按钮所在的.back容器,再获取里面的toggle-content
    const content = this.closest('.back').querySelector('.toggle-content');
    // 切换显示状态
    content.style.display = content.style.display !== 'none' ? 'none' : 'block';
  };
});

额外说明

  • closest('.back')会向上查找最近的.back父元素,确保我们只操作当前卡片内的内容,不会串到其他卡片上。
  • 如果以后要添加更多翻转卡片,这个脚本不需要修改,会自动绑定新的按钮,扩展性更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 17:04:06