gpt4 book ai didi

javascript - XHTML5 中的 SVG : setting attributes with proper namespace

转载 作者:数据小太阳 更新时间:2023-10-29 02:24:57 25 4
gpt4 key购买 nike

TL;DR 总结:使用 setAttribute 是否合适?而不是 setAttributeNS SVG 元素?

详情:
考虑这个嵌入 XHTML5 中的 SVG 图像,它使用 JavaScript 动态创建元素并将元素添加到绘图:http://phrogz.net/svg/svg_in_xhtml5.xhtml

由 JavaScript 创建并附加到 <svg> 的 SVG 元素必须使用...创建元素

var el = document.createElementNS("http://www.w3.org/2000/svg",'foo');

...而不是...

var el = document.createElement('foo');

...以便将它们视为 SVG 元素并在浏览器中呈现。这是合理的,也是可以理解的。然而,根据this page我还应该使用...设置这些元素的属性。

el.setAttributeNS( null, 'foo', 'bar' );

...而不是我目前使用的代码:

el.setAttribute( 'foo', 'bar' );

我所做的工作适用于 Chrome、Safari 和 Firefox。我拥有的是什么合法代码——它是否等同于推荐——或者它只是碰巧由于浏览器的宽容性质而工作,我必须改为使用setAttributeNS有效吗?

最佳答案

只要您不使用命名空间属性(带或不带前缀),您就可以使用 setAttribute。

setAttributeNS 推荐在某种程度上是好的,因为这样您就不必担心使用不同的方法(以及何时使用哪个)。当您需要更改例如 xlink:href 或自定义命名空间属性时,您实际上只需要 setAttributeNS。另一方面,人们确实弄错了 namespace (有时尝试使用例如 svg namespace 而不是 NULL 来表示 svg 属性),所以恕我直言,尚不清楚什么比较容易混淆。

DOM 2 Core这是关于 DOM Level 1 get/setAttribute 方法的:

DOM Level 1 methods are namespace ignorant. Therefore, while it is safe to use these methods when not dealing with namespaces, using them and the new ones at the same time should be avoided.

我可能会补充说,“同时”可能应该读作“在相同的(预期的)属性上同时”,或类似的东西。

除了 svg 标记本身之外,SVG 本身不要求您的脚本“合法”或类似内容,但它确实需要支持某些 DOM 规范,例如 SVG 1.1 中的 DOM 2 Core。

关于javascript - XHTML5 中的 SVG : setting attributes with proper namespace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4882890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com