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

JavaScript按钮内带下划线文本时点击事件失效的原因与解决

问题原因分析与解决方案

问题原因

点击按钮内的<u>文本时,事件的e.target指向的是<u>元素而非外层的.collapsible按钮。当前代码中判断!tgt.matches(".collapsible")就直接返回,导致折叠逻辑无法触发。

解决方案

方案1:通过closest()定位按钮元素

修改JavaScript事件处理逻辑,使用closest()方法从点击的子元素向上查找最近的.collapsible按钮,确保无论点击按钮内的哪个子元素都能触发折叠功能:

const collapse = (elem,forceClose) => {
  const content = elem.nextElementSibling;
  if (!content || !content.matches(".content")) return;
  if (forceClose) elem.classList.remove("active");
  else elem.classList.toggle("active");
  content.style.maxHeight = elem.classList.contains("active") ? content.scrollHeight + "px" : null;
};

const buttons = document.querySelectorAll(".collapsible");
document.getElementById("container").addEventListener("click", e => {
  const tgt = e.target.closest(".collapsible"); // 修改为closest查找按钮
  if (!tgt) return;
  if (tgt.matches(".all")) {
    const close = container.querySelectorAll(".collapsible.active").length > 0;
    buttons.forEach(but => collapse(but,close)); 
  } else {
    collapse(tgt);
  }
});

方案2:用CSS替代<u>标签保留下划线

如果不想修改JS逻辑,可以移除HTML中的<u>标签,通过CSS实现下划线样式,避免按钮内部存在独立子元素:
修改HTML:

<div id="container">
  <button class="collapsible">XXXXXXXXXX <span class="underlined">YYYYYYYYYY</span></button>
  <div class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
</div>

添加CSS:

.content {
  max-height:0;
  overflow:hidden;
}
.underlined {
  text-decoration: underline;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 06:18:20