对于自定义标签在HTML5中是否有效,我一直无法找到一个明确的答案,比如:

<greeting>Hello!</greeting>

我在说明书中什么都没发现:

http://dev.w3.org/html5/spec/single-page.html

而且自定义标记似乎无法使用W3C验证器进行验证。


当前回答

只需使用任何你想要的,而不需要任何dom声明

<container>content here</container>

添加您自己的样式(display:block),它将适用于任何现代浏览器

其他回答

我知道这个问题很老了,但我一直在研究这个主题,尽管上面的一些陈述是正确的,但它们不是创建自定义元素的唯一方法。例如:

<button id="find">click me</button>
<Query? ?attach="find" ?content="alert( find() );" ?prov="Hello there :D" >
I won't be displayed :D
</Query?>

<style type="text/css">

[\?content] {

display: none;

}

</style>

<script type="text/javascript">

S = document.getElementsByTagName("Query?")[0];

Q = S.getAttribute("?content");

A = document.getElementById( S.getAttribute("?attach") );

function find() {

  return S.getAttribute("?prov");

}

(function() {

A.setAttribute("onclick", Q);

})();

</script>

将工作得非常好(在谷歌Chrome, IE, FireFox和移动Safari的新版本)。您所需要的只是一个alpha字符(a-z, a-z)来开始标记,然后您可以使用任何非alpha字符。如果在CSS中,你必须使用“\”(反斜杠)来查找元素,比如需要Query\^{…}。但在JS中,你只是用你看到的来称呼它。我希望这能帮到你。参见这里的例子

- 水貂CBOS

我想指出的是,“有效”这个词在这里有两种不同的含义,其中任何一种都是潜在的,嗯,有效的。

Should an HTML document with custom tags be considered valid HTML5? The answer to this is clearly "no." The spec lists exactly what tags are valid in what contexts. This is why an HTML validator will not accept a document with custom tags, or with standard tags in the wrong places (like an "img" tag in the header). Will an HTML document with custom tags be parsed and rendered in a standard, clearly-defined way across browsers? Here, perhaps surprisingly, the answer is "yes." Even though the document would not technically be considered valid HTML5, the HTML5 spec does specify exactly what browsers are supposed to do when they see a custom tag: in short, the custom tag acts kind of like a <span> - it means nothing and does nothing by default, but it can be styled by HTML and accessed by javascript.

只需使用任何你想要的,而不需要任何dom声明

<container>content here</container>

添加您自己的样式(display:block),它将适用于任何现代浏览器

给出一个反映现代页面的更新答案。

自定义标记是有效的,

1)它们包含一个破折号

<my-element>

2)它们是嵌入的XML

<greeting xmlns="http://example.com/customNamespace">Hello!</greeting>

这里假设你使用的是HTML5 doctype <!doctype html >

考虑到这些简单的限制,现在尽最大努力保持HTML标记的有效性是有意义的(请停止关闭<img>和<hr>这样的标记,除非您使用XHTML doctype,否则这是愚蠢和不正确的,您可能不需要XHTML doctype)。

鉴于HTML5清楚地定义了解析规则,兼容的浏览器将能够处理您扔给它的任何标记,即使它不是严格有效的。

自定义HTML元素是一个新兴的W3标准,我一直在为它做出贡献,它允许你用解析器声明和注册自定义元素,你可以在这里阅读规范:W3 Web Components自定义元素规范。此外,微软支持一个名为X-Tag的库(由前Mozilla开发人员编写)——它使使用Web组件更加容易。