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

点击省略号仅显示对应div,已打开的其他div自动隐藏问题求助

实现点击按钮仅显示对应Div,自动隐藏其他已打开Div的交互

你当前的代码只实现了单个按钮的展开/收起切换,但未处理“关闭其他已打开Div”的逻辑。只需修改JavaScript部分,在点击时先关闭所有已展开的.report,再根据当前按钮对应Div的状态决定是否展开它。

修改后的完整代码

HTML

<div class="main">
  <div class="card">
    <h4>Card</h4>
    <div class="flag">
    <button class="ellipsis">&#8942</button>
    <div class="report">
      <p>Report</p>
      <p>Not-Interested</p>
    </div>
  </div>
  </div>
  <div class="card">
    <h4>Card</h4>
    <div class="flag">
    <button class="ellipsis">&#8942</button>
    <div class="report">
      <p>Report</p>
      <p>Not-Interested</p>
    </div>
  </div>
  </div>
</div>

CSS

.main{
  margin:0;
  padding:0;
  display:flex;
  gap:20px;
}
.card{
  width: 150px;
  height:200px;
  background: coral;
  border:1px solid #000;
  position:relative;
}
.card h4{
  color:#fff;
  top:35%;
  left:40%;
  position:absolute;
}
.card .flag {
  top:0;
  right:15px;
  position:absolute;
}
.flag .report{
  display:none;
  float:left;
  background: #fff;
  padding:0;
  margin-top: 27px;
  margin-right: -5px;
}
.flag .report.show{
  display:block;
}
.card .flag button{
  border:0;
  background:0;
  outline:0;
  font-size:25px;
  color:#fff;
  position:absolute;
}
.report p{
 padding: 2px 5px;
  top:-10px;
  font-size:10px;
  line-height:0.1rem;
  cursor:pointer;
}

JavaScript

const ellipsis = document.querySelectorAll(".ellipsis");
ellipsis.forEach((el) =>
  el.addEventListener("click", (event) => {
    const currentReport = event.currentTarget.parentElement.querySelector(".report");
    const isCurrentOpen = currentReport.classList.contains("show");
    
    // 关闭所有已打开的.report
    document.querySelectorAll(".report.show").forEach(report => {
      report.classList.remove("show");
    });
    
    // 仅当当前Div原本未打开时,才展开它
    if (!isCurrentOpen) {
      currentReport.classList.add("show");
    }
  })
)

核心逻辑说明

  • 点击按钮时,先获取当前按钮对应的.report元素,并记录它是否已处于展开状态
  • 遍历所有带有show类的.report,移除该类以关闭所有已展开的面板
  • 如果当前面板原本未展开,就添加show类展开;如果原本已展开,经过上一步关闭后保持收起状态,实现点击已展开按钮也能关闭的交互

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:47:20