问题描述
问题总结
我正在为一个简单的 html 文档创建一个打印样式表,其中包含 id 引用的标题和锚点来引用这些标题,例如
<h1 id="the-document">The Document</h1>
<h2 id="background">Background</h2>
<h2 id="implementation">Implementation</h2>
<p>For details,see <a href="#background">Background</a>.</p>
打印样式需要使用 css 计数器创建的部分编号,例如
h1 {
counter-reset: section
}
h2:before {
content: counter(section) ". ";
counter-increment: section
}
我尝试将附加到“背景”部分的“1.”也添加到引用该部分的锚点,即结果应该看起来像
文档
1.背景
2.实施
有没有办法添加引用到引用该部分的锚点的部分的计数器?没有 JavaScript?
我的尝试
a[href^=#]:before { content: counter(section) ". "; }
会导致
我知道这可以用 JavaScript 来完成:
let section = 0;
const h2s = Array.from(document.querySelectorAll('h1,h2')).reduce((h2s,h,i) => {
switch (h.nodeName) {
case 'H1': section = 0; break;
case 'H2': h2s[h.id] = ++section; break;
}
return h2s;
},{})
Array.from(document.querySelectorAll('a[href^="#"]')).forEach(_ => _.textContent = `${h2s[_.href.split('#')[1]]}. ${_.textContent}`)
h1 {
counter-reset: section;
}
h2:before {
content: counter(section) ". ";
counter-increment: section;
}
<h1 id="the-document">The Document</h1>
<h2 id="background">Background</h2>
<h2 id="implementation">Implementation</h2>
<p>For details,see <a href="#background">Background</a></p>
它可能会关心谁,我正在 Jekyll 中编写 Markdown(用于 GitHub 页面,因此没有插件)并且宁愿删除该功能也不愿添加 JavaScript 来实现它。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)