> 这是 Momo 主题 1.0.52 的目录功能制作记录。
> 目标是在不破坏原有文章排版和手账模式的前提下,给文章页增加一个可跳转、可高亮、适配暗色模式的右侧目录。
需求
文章页原本是单栏布局。长文章阅读时有两个问题:
1. 读者需要不断往上翻才能找到章节
2. 文章结构没有概览,不知道后面还有哪些内容
希望增加一个右侧目录:
- 桌面端固定在文章右侧
- 可以点击跳到对应标题
- 滚动时高亮当前章节
- 适配 Momo 的奶油纸风格
- 适配夜间模式
- 手机端和窄屏自动隐藏
- 不能破坏碎碎念手账文章的卡片分组
模板结构
把文章和目录放进同一个容器
原来的文章页结构是:
```html
<article class="article">
<!-- 文章 -->
</article>
```改成:
```html
<div class="article-shell">
<article class="article">
<!-- 文章 -->
</article>
<aside class="article-toc" aria-label="文章目录">
<div class="article-toc-inner">
<div class="article-toc-title">目录</div>
<nav class="article-toc-nav" id="article-toc-nav"></nav>
</div>
</aside>
</div>
```不要在原来的 article 内部塞目录,否则目录会跟着正文宽度一起被限制,也不方便做 sticky。
手账文章仍然走原来的模板
post.html 里原本就有碎碎念判断:
```html
<th:block th:fragment="content"
th:with="
diaryCategory=${theme.config.content?.diaryCategory ?: '碎碎念'},
isDiaryPost=${#lists.contains(post.categories.![spec.displayName],
theme.config.content?.diaryCategory ?: '碎碎念')}">
```目录只是加在外层,手账文章的分组逻辑不受影响。需要保证目录脚本在正文分组完成之后再收集标题。
CSS布局
两栏网络
```css
.article-shell {
display: grid;
grid-template-columns: minmax(0, 840px) 224px;
gap: 34px;
width: min(1120px, 100%);
margin: 0 auto;
align-items: start;
}
.article-shell > .article {
width: 100%;
min-width: 0;
margin: 40px 0 60px;
}
```目录宽度固定在 224px 左右,文章列使用 minmax(0, 840px),保证长标题和代码块不会把网格撑坏。
sticky 目录卡
```css
.article-toc {
position: sticky;
top: 110px;
margin-top: 40px;
}
.article-toc-inner {
padding: 16px;
background: rgba(255, 250, 242, .82);
border: 1px dashed var(--line);
border-radius: 16px;
}
```top: 110px 是为了避开顶部 sticky 导航。目录列表本身也要限制高度,内容特别长时在卡片内部滚动:
```css
.article-toc-nav {
display: flex;
flex-direction: column;
gap: 3px;
max-height: calc(100vh - 190px);
overflow-y: auto;
}
```标题层级和选中状态
```css
.article-toc-link {
padding: 5px 7px;
border-left: 2px solid transparent;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
text-decoration: none;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.article-toc-link.toc-level-h2 {
padding-left: 18px;
}
.article-toc-link.toc-level-h3 {
padding-left: 30px;
font-size: 11px;
}
.article-toc-link:hover,
.article-toc-link.is-active {
color: #a93663;
border-left-color: var(--pink);
background: var(--pink-soft);
}
```选中状态用 is-active,不要只依赖 :hover;否则滚动时目录不会有反馈。
暗色模式
目录卡使用主题变量,再补一层夜间覆盖:
```css
html[data-theme="dark"] .article-toc-inner {
background: rgba(23, 20, 42, .9);
border-color: rgba(255, 159, 196, .42);
}
html[data-theme="dark"] .article-toc-title {
color: #f5eaff;
border-bottom-color: rgba(199, 155, 255, .35);
}
html[data-theme="dark"] .article-toc-link:hover,
html[data-theme="dark"] .article-toc-link.is-active {
color: #ff9fc4;
background: #321b39;
}
```移动端隐藏
```css
@media (max-width: 1120px) {
.article-shell {
display: block;
width: 100%;
}
.article-toc {
display: none;
}
}
```手机端优先保证正文宽度。目录不是移动端阅读的刚需,强行放进去会挤压正文。
JavaScript 生成目录
收集标题
从 .post-content 内查找 H1、H2、H3:
```javascript
const content = document.querySelector('.post-content');
const toc = document.querySelector('.article-toc');
const nav = document.querySelector('#article-toc-nav');
const headings = [...content.querySelectorAll('h1, h2, h3')];
if (headings.length < 2) {
toc.hidden = true;
return;
}
```标题少于两个时没有必要显示目录。
给标题补唯一 ID
Halo 文章里的标题有时候已经有 ID,有时候没有。不能直接复用可能重复的 ID:
```javascript
const usedIds = new Set(
[...document.querySelectorAll('[id]')].map((el) => el.id)
);
headings.forEach((heading, index) => {
let baseId = heading.id || `article-heading-${index + 1}`;
let id = baseId;
let suffix = 1;
while (usedIds.has(id)) {
id = `${baseId}-${suffix++}`;
}
usedIds.add(id);
heading.id = id;
});
```生成链接
```javascript
const links = [];
headings.forEach((heading, index) => {
let baseId = heading.id || `article-heading-${index + 1}`;
let id = baseId;
let suffix = 1;
while (usedIds.has(id)) {
id = `${baseId}-${suffix++}`;
}
usedIds.add(id);
heading.id = id;
heading.style.scrollMarginTop = '110px';
const link = document.createElement('a');
link.href = `#${id}`;
link.className = `article-toc-link toc-level-${heading.tagName.toLowerCase()}`;
link.textContent = heading.textContent.trim();
link.addEventListener('click', (event) => {
event.preventDefault();
heading.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.replaceState(null, '', `#${id}`);
setActive(id);
});
nav.appendChild(link);
links.push(link);
});
```scrollMarginTop 是为了点击标题后不会被 sticky 导航挡住。
滚动高亮
用 IntersectionObserver 监听标题进入视口:
```javascript
const setActive = (id) => {
links.forEach((link) => {
link.classList.toggle(
'is-active',
link.getAttribute('href') === `#${id}`
);
});
};
const observer = new IntersectionObserver((entries) => {
const visible = entries
.filter((entry) => entry.isIntersecting)
.sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
if (visible.length) {
setActive(visible[0].target.id);
}
}, {
rootMargin: '-110px 0px -70% 0px',
threshold: [0, 1]
});
headings.forEach((heading) => observer.observe(heading));
setActive(headings[0].id);
```初始时先把第一个标题设为选中,避免页面刚打开时目录没有任何状态。
手账文章的特殊处理
手账文章会把正文按 H1/H2 拆成 .scrapbook-card。因此目录脚本必须放在分组脚本之后执行:
```text
先执行 scrapbook 分组
再执行目录收集
```如果把目录脚本放在前面,收集到的可能是还没分组的原始节点。虽然标题本身还在,但后续 DOM 被替换后,目录链接可能指向已经不存在的节点。
另外,文章里如果有 style/script,分组时必须跳过,否则会出现空白纸卡。目录只收集 H1/H2/H3,不会把这些节点当成标题。
PJAX 下的目录
Momo 使用 PJAX 替换 .site-main。这意味着:
- 每次进入新文章,目录脚本都会重新执行
- 旧的 IntersectionObserver 会自动失效
- 旧的目录不会残留,因为整个正文区域已经被替换
- 新文章标题会重新生成 ID 和链接
需要注意:不要给目录绑定全局重复事件。目录脚本应该保持自执行函数,只处理当前 DOM。
踩过的坑
忘记给标题ID
Halo 编辑器生成的标题有时候没有稳定 ID。目录必须有 ID 才能跳转,所以要在前端补。
手账分组把标题移动了
分组后标题的父节点变成 .scrapbook-card,目录仍然可以在 .post-content 里查询到它们。关键是执行顺序。
ticky 不生效
如果 .article-toc 的父容器设置了 overflow: hidden 或高度被压缩position: sticky 会失效。检查:
```css
.article-shell {
align-items: start;
}
```目录列不要被拉伸成和文章一样高。
点击跳转被导航挡住
需要给标题加 scroll-margin-top:
```css
.post-content h1,
.post-content h2,
.post-content h3 {
scroll-margin-top: 110px;
}
```暗色模式文字看不清
目录卡使用主题变量还不够,选中态和悬停态需要单独覆盖夜间颜色,否则粉色背景上的文字可能对比度不足。
总结
右侧目录看起来只是一个侧边栏,实际涉及四件事:
1. 模板层:文章和目录的容器关系
2. CSS 层:两栏网格、sticky、层级缩进、暗色模式
3. JavaScript 层:标题 ID、目录链接、滚动高亮
4. 主题层:手账分组顺序、PJAX 重新执行、移动端取舍
最值得记住的一点是:**目录脚本一定要在文章正文最终结构稳定之后运行**。否则标题虽然能显示,跳转目标却可能已经变了。
评论