你能在 HTML5 中定义自己的自闭标签吗?

2022-01-18 00:00:00 tags html

我已阅读 此 主题,但我仍然有疑问.有没有办法定义 void 标签?

我试过了:

<icon class="home"/>(知道斜线不是强制性的)

但是,如果这个标签FF关闭后还有文字内容的话.

<icon class="home"/>回家

制作

<icon class="home">回家</icon>

我应该在某个地方定义标签是 void-element 吗?还是用 HTML5 做不到?

解决方案

这不是一个答案,因为它没有完全解决问题,但它不适合评论部分.

/> 中的 / 如果解析为 html5 规范,则浏览器会忽略(MathLM 的 foreign elements 除外SVG,因为对于这个 modules 的元素,它们的规范具有自封闭元素,因此需要保持有效)

规格的相关部分:

  • W3C - HMTL5 - 元素
  • W3C - HMTL5 - 开始标签

(浏览器应该如何处理丢失的标签以及它们忽略 / 的相关部分丢失了,我需要查找这个)

如果元素是 void 元素,则不会生成结束标记,因为它不需要.

对于其他元素,如果缺少结束标记,则会创建它.所以如果你写这样的东西:

<div/>测试</div>

这会导致

<div>测试</div></div>

因为 / 被忽略了.

自定义元素默认为 non-void.我知道 自定义元素 但老实说,我不知道某些浏览器是否已经支持它.但即使是这样,你也会遇到向后兼容的问题.所以我不建议使用它.

即使这样定义一个不以 x- 为前缀的标签名称也是一个坏主意,因为如果稍后由规范添加具有您选择的名称的元素,并且如果它具有其他含义,您将拥有一个问题.

只要我有时间查看规格,我就会提供相应的缺失部分来证明这一点.

I have read this topic, but I still have doubts. Is there any way to define void tag?

I tried this:

<icon class="home"/> (know that slash isn't obligatory)

But, if there is any text content after this tag FF closes them.

<icon class="home"/> Go home

Makes

<icon class="home">Go home</icon>

Should I define somewhere that tag is void-element? Or is it impossible to do with HTML5?

解决方案

This is currently not an answer because it does not fully address the question, but it did not fit into the comment section.

The / in /> is ignored by the browsers if parsed to the html5 specs (except foreign elements of MathLM and SVG, because for the elements of this modules their specs has self enclosing element, so there it needs to stay valid)

Relevant parts of the specs:

  • W3C - HMTL5 - Elements
  • W3C - HMTL5 - Start tags

(The relevant part how browsers should handle missing tags and that they ignore / is missing, i need to look this up)

If the element is a void element no closing tag is generated, because it does not require one.

For the other elements the closing tag is created if it is missing. So if you write something like this:

<div>
    <div/>test
</div>

It will result in

<div>
    <div>test</div>
</div>

Because the / is ignored.

Custom elements are non-void by default. I know there is a draft for Custom Elements but honestly i don't know if it is already supported in some browsers. But even if it is, you will have the problem of backward compatibility. So i would not recommend to use it.

Even so defining a tag name not prefixed with an x- is a bad idea because if later an element is added by the specs with the name you choose and if that has another meaning you will have a problem.

As soon as i have time to look up the specs i'll provide the corresponding missing parts to proof this.

相关文章