在 HTML5 中混合显式和隐式分段时不可能的情况?

Impossible situation when mixing explicit and implicit sectioning in HTML5?

我为 HTML5 找到了 a page about sections and outlines。不能 100% 确定它是官方的,而且页面上说大多数浏览器不遵循它,但我认为这是一个很酷的想法,所以我正在尝试创建代码来显式插入隐式部分并创建大纲。

我遇到的概念性问题类似于隐式和显式分段混合的示例之一(缩写版):

<body>
  <h1>Mammals</h1>
  <h2>Whales</h2>
  ...
  <section>
    <h3>Forest elephants</h3>  
    ...
    <h3>Mongolian gerbils</h3>
    ...
    <h2>Reptiles</h2>
    ...
  </section>
</body>

哪个应该给出:

1. Mammals
   1.1 Whales (implicitly defined by the h2 element)
   1.2 Forest elephants (explicitly defined by the section element)
   1.3 Mongolian gerbils (implicitly defined by the h3 element, which closes the previous section at the same time)
2. Reptiles (implicitly defined by the h2 element, which closes the previous section at the same time)

但是我 运行 遇到了麻烦(开始一个部分 header 然后使用一个不太深的 header )。考虑这个稍微修改过的例子:

<body>
  <h1>Mammals</h1>
  <h2>Whales</h2>
  ...
  <section>
    <h3>Forest elephants</h3>  
    ...
    <h2>Reptiles</h2>
    ...
    <h1>Martians</h2>
    <p>Just being annoying</p>
  </section>
</body>

我该如何处理?最后一个 <h1> 应该在外部范围的 <h0> 级别结束,它不存在。

(我个人认为以 <h3> 开头的明确部分只允许 <h3><h4><h5><h6>,但这并没有重现这个例子,我想用 'official' 的方式来做。)

大纲算法通过简单地不允许分段元素中的标题元素高于分段元素本身来解决这个问题。来自 spec:

When entering a heading content element

If the current section has no heading, let the element being entered be the heading for the current section.

Otherwise, if the element being entered has a rank equal to or higher than the heading of the last section of the outline of the current outline target, or if the heading of the last section of the outline of the current outline target is an implied heading, then create a new section and append it to the outline of the current outline target element, so that this new section is the new last section of that outline. Let current section be that new section. Let the element being entered be the new heading for the current section.

例如,如果您有一个 <h3> 作为一个部分的第一个标题,那么在同一部分中跟随它的任何 <h2><h1> 将被同等对待,创建与第一个分开的隐式部分。只有 <h4><h6> 会在不开始新部分的情况下创建隐式小节。

您的第一个示例实际上生成了以下大纲:

1. Mammals
   1.1 Whales
   1.2 Forest elephants
   1.3 Mongolian gerbils
   1.4 Reptiles

您的第二个示例生成以下大纲:

1. Mammals
   1.1 Whales
   1.2 Forest elephants
   1.3 Reptiles
   1.4 Martians

分节内容元素中的隐含部分无法"break out"创建higher-level条目。他们要么创建同级条目(如果它是具有相同或更高等级的标题元素),要么创建 child 条目(如果它是具有较低等级的标题元素)。

所以你的两个例子都创建了这个大纲:

1. Mammals
   1.1 Whales
   1.2 Forest elephants
   1.3 Mongolian gerbils [resp. Reptiles]
   1.4 Reptiles [resp. Martians]

demo of the HTML5 Outliner (which I recommend) 似乎同意。