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

如何将hover触发的表格弹窗改为点击触发并添加右上角取消按钮

修改后完整实现

CSS 代码

.dropdown {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  padding: 28px 16px 12px; /* 顶部预留关闭按钮位置 */
  z-index: 1;
}
/* 用active类控制显隐,替换原hover触发规则 */
.dropdown-content.active {
  display: block;
}
/* 关闭按钮样式 */
.close-btn {
  position: absolute;
  top: 4px;
  right: 8px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  color: #666;
}
.close-btn:hover {
  color: #000;
}

HTML 代码

<div class="dropdown">
  <span>点击我显示表格</span>
  <div class="dropdown-content">
    <!-- 新增右上角关闭按钮 -->
    <span class="close-btn">×</span>
    <table id="t1">
      <tr>
        <th id="q">Quon</th>
        <th id="q1">SE</th>
        <th id="q2">SE</th>
        <th id="q3">SE</th>
        <th id="q4">SETY</th>
      </tr>
      <tr id="df3">
        <th id="i1">Ict</th>
        <td id="i2">as</td>
        <td id="i3">ds</td>
        <td id="i4">fd</td>
        <td id="i5" rowspan="2">dfd</td>
      </tr>
      <tr>
        <th id="j1">Juion</th>
        <td id="j2">How</td>
        <td id="j3">How</td>
        <td id="j4">How</td>
      </tr>
    </table>
  </div>
</div>

JS 代码

// 获取对应DOM元素
const dropdownTrigger = document.querySelector('.dropdown span');
const dropdownContent = document.querySelector('.dropdown-content');
const closeBtn = document.querySelector('.close-btn');

// 点击触发文本切换弹窗显隐
dropdownTrigger.addEventListener('click', (e) => {
  e.stopPropagation();
  dropdownContent.classList.toggle('active');
});

// 点击关闭按钮隐藏弹窗
closeBtn.addEventListener('click', () => {
  dropdownContent.classList.remove('active');
});

// 可选拓展:点击弹窗以外区域自动关闭弹窗
document.addEventListener('click', () => {
  dropdownContent.classList.remove('active');
});

// 点击弹窗内部不触发关闭
dropdownContent.addEventListener('click', (e) => {
  e.stopPropagation();
});

核心调整说明:

  • 移除了原CSS中hover触发显示的规则,改用类名切换控制显隐,适配点击触发需求
  • 新增右上角关闭按钮及对应样式,调整弹窗内边距避免按钮遮挡表格内容
  • 新增交互逻辑覆盖点击触发、点击关闭、点击外部区域关闭的常用使用场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:24:02