【问题标题】:Why won't dynamic SVG work if not handled via createElementNS如果不通过 createElementNS 处理,为什么动态 SVG 不能工作
【发布时间】:2016-09-09 07:29:55
【问题描述】:

我试图在纯 JS 中操作 SVG,发现如果我不使用 createElementNSsetAttributeNS 之类的方法,它的行为将无法达到预期。

<svg id="mydsvg" width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>

上述标记完美运行。但是如果您尝试通过以下代码添加另一个圈子,您将看不到它。

var circle = createElement('circle');
circle.setAttribute('cx', 50);
....
document.getElementById('mysvg').appendChild(circle);

但如果你使用createElementNSsetAttributeNS,它会按预期工作。

最糟糕的是,createElementcreateElementNS 都会创建相同的 DOM 文本。

【问题讨论】:

    标签: javascript svg namespaces


    【解决方案1】:

    它不起作用,因为规范说 SVG 元素必须存在于 SVG 命名空间中,而 createElement 在 html 命名空间中创建元素。解析器如何知道您是要创建一个与 src 属性一起使用的 html &lt;a&gt; 元素还是需要 `xlink:href 属性的 SVG &lt;a&gt; 元素。

    在命名空间未序列化的 html 中,事情看起来是一样的。在命名空间被序列化的 XML 中,它们不会。

    html 中的 SVG 看起来像这样......

    <svg id="mydsvg" width="100" height="100">
      <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
    </svg>
    

    SVG 作为一个独立的文档看起来像这样

    <svg xmlns="https://www.w3.org/2000/svg" id="mydsvg" width="100" height="100">
      <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
    </svg>
    

    圆圈继承其父级的命名空间。

    【讨论】:

    • 真正完整的答案。谢谢。如果您可以为最后一句显示一个小代码示例,那将非常有用。
    猜你喜欢
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多