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

如何在不指定<summary>元素时覆盖<details>标签的默认摘要文本

如何在无元素时覆盖
的默认摘要文本

方法1:CSS+JS结合实现自定义摘要(保留原标题位置)

浏览器默认的"Details"文本属于内部渲染内容,没法直接通过CSS选中修改,但可以通过以下方式替换:

  • 先用CSS隐藏收起状态下的内部内容,同时用伪元素插入自定义文本;
  • 配合JS提取内部标题文本,作为伪元素的内容来源。

示例代码:

/* 收起状态下隐藏details内部的所有元素 */
details:not([open]) > * {
  display: none;
}

/* 用伪元素显示自定义摘要文本 */
details::before {
  content: attr(data-summary);
  cursor: pointer;
  font-weight: 600;
  margin: 8px 0;
}

/* 展开后隐藏伪元素,显示原内容 */
details[open]::before {
  display: none;
}
// 给每个details添加data-summary属性,取值为内部的标题文本
document.querySelectorAll('details').forEach(detail => {
  const heading = detail.querySelector('h2, h3, h4');
  if (heading) {
    detail.setAttribute('data-summary', heading.textContent.trim());
  }
});

方法2:纯JS动态插入元素(语义更规范)

直接给没有summary的details元素动态插入summary标签,把内部标题的文本(或标题元素本身)移进去,完全替代默认的"Details"文本:

document.querySelectorAll('details:not(:has(summary))').forEach(detail => {
  const summary = document.createElement('summary');
  const heading = detail.querySelector('h2, h3, h4');
  
  if (heading) {
    // 方案A:复制标题文本,保留原标题在原位
    summary.textContent = heading.textContent.trim();
    detail.insertBefore(summary, detail.firstChild);
    
    // 方案B:把标题直接移到summary里(原位置不再显示标题)
    // detail.insertBefore(summary, heading);
    // summary.appendChild(heading);
  }
});

这种方法符合HTML语义规范,浏览器会自动识别summary作为折叠面板的标题,完全覆盖默认文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 04:45:05