Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

markdown - include css counters in anchor links?

Problem summary

I'm creating a print stylesheet for a simple html document with id-referenced headers and anchors to reference these headers, like

<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>

The print styles need section numbers that are created with css counters like

h1 {
  counter-reset: section
}
h2:before {
  content: counter(section) ". ";
  counter-increment: section
}

I try to add the "1. " that is prepended to the "Background" section also to the anchor that references the section, i.e. the result should look like

The Document

1. Background

2. Implementation

For details, see 1. Background

Is there a way to add the counter of the section that is referenced to the anchor that references the section? Without JavaScript?

What I've tried

Adding the current counter to all references results in the wrong counter value, like

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

would result in

For details, see 2. Background

I know this could be done with 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...