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

如何在R Markdown中同时实现浮动TOC与文档开头固定TOC?

实现R Markdown HTML文档同时显示浮动TOC与开头固定目录

方案1:使用bookdown::html_document2(推荐)

这是最省心的方法,bookdown扩展原生支持双目录结构,无需额外编写代码:

在R Markdown的YAML头部配置如下:

---
title: "双目录演示文档"
output:
  bookdown::html_document2:
    toc: true          # 启用基础目录功能
    toc_float: true    # 开启右侧浮动侧边TOC
    number_sections: true # 可选:给标题添加编号,让目录层级更直观
---

生成的文档会自动包含:

  • 文档开头的固定目录(默认带标题编号,可通过number_sections: false关闭)
  • 页面右侧的浮动侧边TOC(滚动时固定,点击可快速跳转至对应章节)

方案2:原生html_document结合自动生成目录

如果不想依赖bookdown,可以通过原生输出格式+少量R代码实现自动生成开头固定目录:

  1. 先在YAML中保留浮动TOC配置:
---
title: "双目录演示文档"
output:
  html_document:
    toc: true
    toc_float: true
---
  1. 在文档开头插入以下R代码块(自动提取所有标题生成固定目录):
```{r echo=FALSE, results='asis', message=FALSE}
library(stringr)

# 读取当前R Markdown文件内容,提取所有标题
md_file <- knitr::current_input()
lines <- readLines(md_file)
headings <- lines[grepl("^#", lines)]

# 生成Markdown格式的固定目录
cat("# 目录\n\n")
for (h in headings) {
  # 计算标题层级(#的数量减1)
  level <- str_count(h, "#") - 1
  # 提取标题文本
  heading_text <- str_trim(str_remove(h, "^#+"))
  # 生成锚点(兼容R Markdown的自动锚点规则)
  anchor <- str_to_lower(str_replace_all(heading_text, "\\s+", "-"))
  # 输出目录项
  cat(strrep("  ", level - 1), "- [", heading_text, "](#", anchor, ")\n", sep = "")
}
注意:需要提前安装`stringr`包,代码会自动识别文档中所有`#`开头的标题,生成对应层级的目录项。

## 样式自定义(可选)
如果觉得默认的固定目录样式不协调,可以添加自定义CSS调整:
```css
<style>
#目录 {
  margin: 2rem 0;
  padding: 1.5rem;
  border: 1px solid #eaecef;
  border-radius: 6px;
  background-color: #f8f9fa;
}
#目录 ul {
  list-style: none;
  padding-left: 1.2rem;
}
</style>

将这段代码放在文档开头的{css echo=FALSE}代码块中即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:57:11