跳到主要内容
版本:3.8.1

标题和目录

Markdown 标题

你可以使用常规的 Markdown 标题。

## Level 2 title

### Level 3 title

#### Level 4 title

每个 Markdown 标题都将显示为目录项。

标题 ID

每个标题都有一个 ID,可以自动生成或显式指定。标题 ID 允许你链接到 Markdown 或 JSX 中的特定文档标题。

[link](#heading-id)
<Link to="#heading-id">link</Link>

默认情况下,Docusaurus 会根据标题文本为你生成标题 ID。例如,### Hello World 的 ID 将是 hello-world

生成的 ID 存在一些限制

  • ID 可能看起来不太好
  • 你可能想更改或翻译文本,而无需更新现有 ID

一种特殊的 Markdown 语法允许你设置显式标题 ID

### Hello World {#my-explicit-id}
提示

使用write-heading-ids CLI 命令为所有 Markdown 文档添加显式 ID。

避免 ID 冲突

生成的标题 ID 将保证在每个页面上都是唯一的,但如果你使用自定义 ID,请确保每个 ID 在每个页面上只出现一次,否则将会有两个具有相同 ID 的 DOM 元素,这违反了 HTML 语义,并会导致某个标题无法链接。

目录标题级别

每个 Markdown 文档的右上角都会显示一个目录。默认情况下,此目录仅显示 h2 和 h3 标题,这对于页面结构的概述应该足够了。如果你需要更改显示的标题范围,可以自定义最小和最大标题级别——无论是按页面还是全局设置。

要为特定页面设置标题级别,请使用 toc_min_heading_leveltoc_max_heading_level 的 Front Matter。

myDoc.md
---
# Display h2 to h5 headings
toc_min_heading_level: 2
toc_max_heading_level: 5
---

要为所有页面设置标题级别,请使用 themeConfig.tableOfContents 选项。

docusaurus.config.js
export default {
themeConfig: {
tableOfContents: {
minHeadingLevel: 2,
maxHeadingLevel: 5,
},
},
};

如果你已全局设置了选项,仍然可以通过 Front Matter 在本地覆盖它们。

注意

themeConfig 选项将应用于站点上的所有目录,包括内联目录,但 Front Matter 选项仅影响右上角的目录。你需要使用 minHeadingLevelmaxHeadingLevel 属性来自定义每个 <TOCInline /> 组件。

内联目录

得益于 MDX,还可以直接在 Markdown 文档中显示内联目录。

toc 变量在任何 MDX 文档中都可用,并包含 MDX 文档的所有标题。默认情况下,只有 h2h3 标题会显示在目录中。你可以通过为单个 TOCInline 组件设置 minHeadingLevelmaxHeadingLevel 来更改可见的标题级别。

import TOCInline from '@theme/TOCInline';

<TOCInline toc={toc} />

toc 全局变量只是标题项的列表

declare const toc: {
value: string;
id: string;
level: number;
}[];

请注意,toc 全局变量是一个扁平数组,因此你可以轻松地删除不需要的节点或插入额外的节点,并创建新的目录树。

import TOCInline from '@theme/TOCInline';

<TOCInline
// Only show h2 and h4 headings
toc={toc.filter((node) => node.level === 2 || node.level === 4)}
minHeadingLevel={2}
// Show h4 headings in addition to the default h2 and h3 headings
maxHeadingLevel={4}
/>

自定义目录生成

目录是通过使用 Remark 插件解析 Markdown 源生成的。存在已知的一些边缘情况,它会生成假阳性和假阴性。

可隐藏区域内的 Markdown 标题仍会显示在目录中。例如,Tabsdetails 内的标题将不会被排除。

非 Markdown 标题将不会显示在目录中。这可以用来解决上述问题。

<details>
<summary>Some details containing headings</summary>
<h2 id="#heading-id">I'm a heading that will not show up in the TOC</h2>

Some content...

</details>

人体工程学地插入额外标题或忽略某些标题的功能正在开发中。如果此功能对你很重要,请在此issue中报告你的用例。


警告

以下只是为了让当前页面有更多目录项可用的一些虚拟内容。

示例章节 1

Lorem ipsum

示例小节 1 a

Lorem ipsum

示例小小节 1 a I

示例小小节 1 a II

示例小小节 1 a III

示例小节 1 b

Lorem ipsum

示例小小节 1 b I

示例小小节 1 b II

示例小小节 1 b III

示例小节 1 c

Lorem ipsum

示例小小节 1 c I

示例小小节 1 c II

示例小小节 1 c III

示例章节 2

Lorem ipsum

示例小节 2 a

Lorem ipsum

示例小小节 2 a I

示例小小节 2 a II

示例小小节 2 a III

示例小节 2 b

Lorem ipsum

示例小小节 2 b I

示例小小节 2 b II

示例小小节 2 b III

示例小节 2 c

Lorem ipsum

示例小小节 2 c I

示例小小节 2 c II

示例小小节 2 c III

示例章节 3

Lorem ipsum

示例小节 3 a

Lorem ipsum

示例小小节 3 a I

示例小小节 3 a II

示例小小节 3 a III

示例小节 3 b

Lorem ipsum

示例小小节 3 b I

示例小小节 3 b II

示例小小节 3 b III

示例小节 3 c

Lorem ipsum

示例小小节 3 c I

示例小小节 3 c II

示例小小节 3 c III