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

<greeting>Hello!</greeting>

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

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

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


当前回答

自定义标记在HTML5中无效。但目前浏览器支持解析它们,你也可以使用css来使用它们。因此,如果你想为当前的浏览器使用自定义标记,那么你可以。但是,一旦浏览器实现了严格用于解析HTML内容的W3C标准,这种支持可能就会消失。

其他回答

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

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.

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

<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

自定义元素规范可以在Chrome和Opera中使用,也可以在其他浏览器中使用。它提供了一种以正式方式注册自定义元素的方法。

自定义元素是可以定义的DOM元素的新类型 作者。与无状态且短暂的装饰器不同,自定义 元素可以封装状态并提供脚本接口。

自定义元素是更大的W3规范Web组件的一部分,另外还有模板、HTML导入和影子DOM。

Web组件使Web应用程序作者能够使用 视觉的丰富程度和交互性是CSS无法实现的 单独使用,并且易于组合和重用,而不可能使用脚本 今天库。

但是,在谷歌开发人员的这篇关于自定义元素v1的优秀通览文章中:

自定义元素的名称必须包含破折号(-)。因此<x-tags>、<my-element>和<my-awesome-app>都是有效名称,而<tabs>和<foo_bar>则不是。这个需求是为了让HTML解析器能够区分自定义元素和常规元素。当新标签添加到HTML中时,它还可以确保向前兼容性。

一些资源

Web组件示例可从https://WebComponents.org获得 WebComponents.js充当了Web组件的填充,直到它们在任何地方都得到支持。参见WebComponents.js github页面和web浏览器支持表。

这是可能的,也是允许的:

用户代理必须处理它们不处理的元素和属性 理解为语义中立的;将它们留在DOM中(用于DOM 处理器),并根据CSS(对于CSS处理器)对它们进行样式化, 但并没有从中推断出任何意义。

http://www.w3.org/TR/html5/infrastructure.html#extensibility-0

但是,如果你想要增加交互性,你需要让你的文档无效(但仍然是完整的功能),以适应IE的7和8。

见http://blog.svidgen.com/2012/10/building-custom-xhtml5-tags.html(我的博客)

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

<container>content here</container>

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