如何在动态创建html时实现分层标题组织

How to achieve hierarchical heading organization when dynamically creating html?

本文关键字:分层 实现 标题 html 动态 创建      更新时间:2023-12-23

wcag 2.0规则之一是标题元素,即h1/h2/h3/等。,应指明文档结构。这意味着你不能跳过一个级别,例如:

<h1>main heading</h1>
...
<h3>subheading</h3>

是无效的,因为在h1和h3之间没有h2元素。这是有效的(根据http://achecker.ca/checker/index.php),即使h2在区间元素内:

<h1>Structure test: h1</h1>
<section>
  <h2>section heading: h2</h2>
</section>
<h3>2nd sub-sub-heading: h3</h3>

以下示例无效,因为最后一个h3跟在h1:之后

<h1>Structure test: h1</h1>
<h2>sub-heading: h2</h2>
<h3>sub-sub-heading: h3</h3>
<section>
  <h1>section heading: h1</h1>
</section>
<h3>2nd sub-sub-heading: h3</h3>

我正在编写javascript,它将添加包含标题元素的内容,我想知道我应该如何选择我应该使用的标题元素(哪个级别),这样我就不会使文档无效?

在HTML5中,您可以在section元素中使用h1元素来定义您的结构:

<section>
    <h1>Blah</h1>
    <p>Asdf asdf...</p>
    <section>
        <h1>Bleh</h1>
        <p>Asdf again...</p>
    </section>
</section>
<section>
    <h1>Another header</h1>
    <p>Qwerty...</p>
</section>

将样式应用于它比较困难(因为您需要依赖类或一堆section>section>h1 CSS选择器),但我认为这是解决问题的最简单方法。