在锚链接中包含 css 计数器?

问题描述

问题总结

我正在为一个简单的 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.实施

详情见1. Background

有没有办法添加引用到引用该部分的锚点的部分的计数器?没有 JavaScript?

我的尝试

将当前计数器添加到所有引用会导致错误的计数器值,例如

a[href^=#]:before { content: counter(section) ". "; }

会导致

详情见2. Background

我知道这可以用 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 (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...