【发布时间】: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] 变量时,我注意到 <title>、<desc> 和 <metadata> 标记在生成的 HTMLCollection 对象(在 Firefox 中)中被正确解析。
但不知何故 <animate> 标签不是,在尝试访问 animate 变量时导致错误(空,就好像标签不存在一样)。
SVG 相当大(6Mb~),但我不明白为什么 SAX 解析器会省略这个标记。
有人有线索吗 ?
【问题讨论】:
-
我无法重现这个问题。但是“repeatCount”必须[大于 0](developer.mozilla.org/en-US/docs/Web/SVG/Attribute/repeatCount)。此外,您可能需要检查
<line>是否包含<animate>标签,如下所示:if(animate.length) {animate[0].setAttribute("repeatCount", "0.0")}。如果问题仍然存在,请添加一个正在运行的 sn-p。 -
我在线运行了 sn-p,代码中没有错误:可能问题出在 XML 解析端?
标签: javascript xml svg