由于某种原因,我的 spinner.svg 在使用 xlink:href
时没有动画。将 SVG 嵌入页面并使用 xlink:href
似乎工作正常,如下面的代码片段所示。
问题:静态(而且是实心!)旋转器而不是动画
为什么 SVG 的动画标签突然不生效? 由于图像实际上正在显示,因此引用必须有效。
编辑:这可能与阴影 dom 和外部参照有关吗?
According to Sara Soueidan “目标元素必须是当前 SVG 文档片段的一部分”。我可能会重载“文档片段”的含义,但对我来说文档片段属于 Shadow DOM 领域,并且我怀疑使用 <use>
时 SMIL 动画可能无法工作由此产生的声明?
工作版本
.xlinked {
color: green;
}
img {
color: red; // not taking effect - of course! just a test.
}
.embedded {
color: blue;
}
<h1>xlink local</h1>
<svg class="xlinked">
<!-- could not get this external reference to work?
<use xlink:href="http://imgh.us/spinner_1.svg" />
-->
<use xlink:href="#spinner" />
</svg>
<h1>embedded</h1>
<div class="embedded">
<svg id="embedded" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
<circle cx="50" cy="50" r="45" stroke="rgba(43,43,43,0.3)" fill="none" stroke-width="10" stroke-linecap="round"/>
<circle cx="50" cy="50" r="45" stroke="currentColor" fill="none" stroke-width="6" stroke-linecap="round">
<animate attributeName="stroke-dashoffset" dur="2s" repeatCount="indefinite" from="0" to="502"/>
<animate attributeName="stroke-dasharray" dur="2s" repeatCount="indefinite" values="150.6 100.4;1 250;150.6 100.4"/>
</circle>
</svg>
</div>
<h1>img</h1>
<img src="http://imgh.us/spinner_1.svg" />
<h1>External absolute xlink (not working)</h1>
<svg>
<!-- could not get this external reference to work. should be the same as a local reference? -->
<use xlink:href="http://imgh.us/spinner_1.svg" />
</svg>
<h1>Source SVG with symbols for xlink reference </h1>
<svg xmlns="http://www.w3.org/2000/svg"><symbol id="spinner" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid"><circle cx="50" cy="50" r="45" stroke="rgba(43,43,43,0.3)" fill="none" stroke-width="10" stroke-linecap="round"/><circle cx="50" cy="50" r="45" stroke="currentColor" fill="none" stroke-width="6" stroke-linecap="round"><animate attributeName="stroke-dashoffset" dur="2s" repeatCount="indefinite" from="0" to="502"/><animate attributeName="stroke-dasharray" dur="2s" repeatCount="indefinite" values="150.6 100.4;1 250;150.6 100.4"/></circle></symbol></svg>
最佳答案
在 SVG1.1 中,Use 元素需要引用 SVG 片段而不是 SVG URL。尝试将 id 属性添加到外部 SVG 文件的根 svg 元素,并将哈希字符串添加到 use 元素的 href 值,如下所示。
外部 svg(spinner_1.svg)
<svg xmlns="http://www.w3.org/2000/svg" id="root">
<!--svg structure-->
</svg>
html 使用外部 SVG 文件
<svg>
<use xlink:href="http://imgh.us/spinner_1.svg#root" />
</svg>
注意:在SVG2中,您可以将SVG URL设置为use元素的href属性。请参阅https://www.w3.org/TR/2016/CR-SVG2-20160915/struct.html#UseElement
关于animation - 为什么使用xlink时SVG动画停止:href for external file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42246883/