SVG 文档支持自定义数据属性吗?

在 HTML5中,元素可以有任意的元数据存储在 XML 属性中,这些属性的名称以 data-开头,例如 <p data-myid="123456">。这也是 SVG 规范的一部分吗?

在实践中,这种技术在许多地方都可以很好地用于 SVG 文档。但是我想知道它是否是官方 SVG 规范的一部分,因为它的格式还很年轻,浏览器之间仍然存在很多不兼容性,特别是在移动设备上。因此,在开始编写代码之前,我想知道未来的浏览器是否会支持这一点。

我发现工作组邮件列表中的 这条信息说他们“希望(他们)会”支持它。这是正式的吗?

31166 次浏览

there is a more general mechanism.

svg supports desc elements which may contain arbitrary xml from other namespaces. link instances of this elements or child nodes from you own namespace by dependent ids or refid attributes.

this is the relevant part of the spec (5.4).

The data-* attribute is part of HTML5. It’s not a generic XML attribute.

The current SVG W3C Recommendation is SVG 1.1 (from 2011-08). It doesn’t allow this attribute, as you can check in the attributes list.

The same is the case for the SVG 2 Working Draft (from 2012-08). Update (2015): It seems that it’s intended to support data-* attributes in SVG 2 (currently still a Working Draft).

While other answers are technically correct, they omit the fact that SVG provides an alternative mechanism for data-*. SVG allows any attribute and tag to be included, as long as it doesn't conflict with existing ones (in other words: you should use namespaces).

To use this (equivalent) mechanism:

  • use mydata:id instead of data-myid, like this: <p mydata:id="123456">
  • make sure you define the namespace in SVG opening tag, like this: <svg xmlns:mydata="http://www.myexample.com/whatever">

EDIT: SVG2, currently W3C Candidate Recommendation (04 October 2018), will support data- directly (without namespaces, the same as HTML). It will take some time before the support is widespread though. Thanks @cvrebert for pointing this out.