Typecho配置文章自动添加目录
目录
官方默认主题,通过js生成toc目录的过程。
环境
- Typecho版本:
1.2.1 - 主题:
Typecho Replica Theme(默认主题) - 安装目录:
/opt/typecho
配置方式:
- 1.直接编辑主题外观
- 2.直接登陆服务器,编辑主题文件 (默认主题目录:
/opt/typecho/usr/themes/default)
这里是通过web后台页面直接编辑网站外观进行配置的。
1.post.php中添加 目录 区域
<div id="toc-container">
<div id="toc-title">目录</div>
<div id="toc"></div>
</div>结构
<li><?php _e('分类: '); ?><?php $this->category(','); ?></li>
</ul>
<div id="toc-container">
<div id="toc-title">目录</div>
<div id="toc"></div>
</div>
<div class="post-content" itemprop="articleBody">
<?php $this->content(); ?>
</div>
<p itemprop="keywords" class="tags"><?php _e('标签: '); ?><?php $this->tags(', ', true, 'none'); ?></p>
</article>2.footer.php文件中添加js内容
<script>
document.addEventListener("DOMContentLoaded", function () {
const content = document.querySelector(".post-content");
const toc = document.getElementById("toc");
if (!content || !toc) return;
const headers = content.querySelectorAll("h2, h3, h4");
if (headers.length === 0) {
document.getElementById("toc-container").style.display = "none";
return;
}
let tocHtml = "<ul>";
let lastLevel = 2;
headers.forEach((el, index) => {
const level = parseInt(el.tagName.substring(1)); // h2→2
const id = "toc-" + index;
el.id = id;
if (level > lastLevel) {
tocHtml += "<ul>";
} else if (level < lastLevel) {
tocHtml += "</ul>";
}
tocHtml += `<li><a href="#${id}">${el.innerText}</a></li>`;
lastLevel = level;
});
tocHtml += "</ul>";
toc.innerHTML = tocHtml;
});
</script>3.style.css中添加样式
/*
* 文章目录 TOC(优化版)
*/
#toc-container {
border: 1px solid #eee;
border-radius: 6px;
padding: 16px;
margin: 24px 0; /* 上下留白 */
background: #fafafa;
box-shadow: 0 2px 8px rgba(0,0,0,0.03); /* 卡片感 */
}
/* 标题 */
#toc-title {
font-weight: 600;
font-size: 16px;
margin-bottom: 12px;
color: #222;
}
/* 列表整体 */
#toc ul {
list-style: none;
padding-left: 12px;
margin: 0;
border-left: 2px solid #eee;
}
/* 每一项 */
#toc li {
margin: 8px 0; /* 行距加大 */
line-height: 1.6;
}
/* 链接 */
#toc a {
text-decoration: none;
color: #555;
font-size: 14px;
display: inline-block;
transition: all 0.2s;
}
/* hover效果 */
#toc a:hover {
color: #007bff;
transform: translateX(2px); /* 轻微动效 */
}
/* 当前章节高亮 */
#toc a.active {
color: #007bff;
font-weight: 600;
}
/* 层级缩进 */
#toc li ul {
margin-left: 12px;
}4.验证
此时就可以去打开文章查看,文章内容上方已经添加了目录展示。
如果样式不生效,可以是缓存导致,清理浏览器缓存后再次刷新即可正常展示。