【问题标题】:animate SVG tag not parsed from JavaScript未从 JavaScript 解析的动画 SVG 标记
【发布时间】:2022-12-13 07:14:34
【问题描述】:

我在使用以下 JavaScript 代码解析 SVG 动画标签时遇到问题:

var lines = document.getElementsByTagName("line");
var i;
for (i=0;i<lines.length;i++){
    if (lines[i].hasAttribute("id")){
        if (lines[i].getAttribute("id").startsWith("CDV_"))
        {
            animate = lines[i].getElementsByTagName("animate");
            animate[0].setAttribute("repeatCount", "0.0");
        }
    }
}

要解析的 XML 如下(它包含其中几个块):

<line id="CDV_z148#3" stroke="rgb(0,220,228)" stroke-width="3" visibility="visible" x1="404.0" x2="833.0" y1="1255.0" y2="1255.0">
    <title>CDV_z148</title>
    <desc>Direction</desc>
    <metadata>
        <route/>
    </metadata>
    <animate attributeName="stroke" attributeType="CSS" dur="1s" from="rgb(0,220,228)" id="CDV_z148#3" repeatCount="indefinite" to="white"/>
</line>

在控制台中打印 lines[i] 变量时,我注意到 &lt;title&gt;&lt;desc&gt;&lt;metadata&gt; 标记在生成的 HTMLCollection 对象(在 Firefox 中)中被正确解析。

但不知何故 &lt;animate&gt; 标签不是,在尝试访问 animate 变量时导致错误(空,就好像标签不存在一样)。

SVG 相当大(6Mb~),但我不明白为什么 SAX 解析器会省略这个标记。

有人有线索吗 ?

【问题讨论】:

  • 我无法重现这个问题。但是“repeatCount”必须[大于 0](developer.mozilla.org/en-US/docs/Web/SVG/Attribute/repeatCount)。此外,您可能需要检查 &lt;line&gt; 是否包含 &lt;animate&gt; 标签,如下所示:if(animate.length) {animate[0].setAttribute("repeatCount", "0.0")}。如果问题仍然存在,请添加一个正在运行的 sn-p。
  • 我在线运行了 sn-p,代码中没有错误:可能问题出在 XML 解析端?

标签: javascript xml svg


【解决方案1】:

在浏览器的上下文中,这在解析 DOM 时可以正常工作。

var lines = document.getElementsByTagName("line");

for (var i = 0; i < lines.length; i++) {
  if (lines[i].hasAttribute("id")) {
    if (lines[i].getAttribute("id").startsWith("CDV_")) {
      animate = lines[i].getElementsByTagName("animate");
      animate[0].setAttribute("repeatCount", "0.0");
      console.log(animate[0].outerHTML);
    }
  }
}
<line id="CDV_z148#3" stroke="rgb(0,220,228)" stroke-width="3" visibility="visible" x1="404.0" x2="833.0" y1="1255.0" y2="1255.0">
  <title>CDV_z148</title>
  <desc>Direction</desc>
  <metadata>
    <route/>
  </metadata>
  <animate attributeName="stroke" attributeType="CSS" dur="1s" from="rgb(0,220,228)" id="CDV_z148#3" repeatCount="indefinite" to="white" />
</line>

【讨论】:

    猜你喜欢
    • 2016-05-28
    • 1970-01-01
    • 2016-11-19
    • 2019-06-28
    • 2010-11-14
    • 2021-09-01
    • 2022-10-19
    • 2021-11-01
    • 2018-12-11
    相关资源
    最近更新 更多