css - 在锚链接中包含 CSS 计数器?
问题描述
问题总结
我正在为一个简单的 html 文档创建一个打印样式表,其中包含 id-referenced headers 和 anchors 来引用这些 headers,比如
<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. 实施
详见1. 背景
有没有办法将引用的部分的计数器添加到引用该部分的锚点?没有 JavaScript?
我试过的
将当前计数器添加到所有引用会导致错误的计数器值,例如
a[href^=#]:before { content: counter(section) ". "; }
会导致
详见2. 背景
我知道这可以用 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 来实现它。
解决方案
推荐阅读
- c# - 检查字符串是否不以 List 中的任何字母开头
- c# - 如何从方法中返回多个值?
- php - 使用 cron 调度程序的 Cron 作业不工作 - Wordpress
- python - 我已经设置了一个 RNG 和一个继续按钮,但它不会在继续后更新结果
- html - 谷歌云平台上的重叠图像
- swift - Swift Sqlite 在 blob 列中插入 null
- javascript - d3.event 在模块化 d3 项目中为空
- tfs - TFS(本地)- 部署:Windows 机器文件复制
- javascript - 在我的函数中,它运行 document.write 10 次我指定
- windows - OpenCV 错误:找不到 CMAKE_C_COMPILER