首页 > 解决方案 > 在锚链接中包含 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 来实现它。

标签: cssmarkdownjekyllcss-counter

解决方案


推荐阅读