Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>

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

1 Answer

等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...