我在SVG的defs标签中有以下LinearGradient:
<defs>
<linearGradient id="left-to-right">
<stop offset="0" stop-color="#000000">
<animate dur="1s" attributeName="offset" fill="freeze" from="0" to="1" />
</stop>
<stop offset="0" stop-color="#fff">
<animate dur="1s" attributeName="offset" fill="freeze" from="0" to="1" />
</stop>
</linearGradient>
<linearGradient id="right-to-left">
<stop offset="0" stop-color="#000000">
<animate dur="1s" attributeName="offset" fill="freeze" from="1" to="0" />
</stop>
<stop offset="0" stop-color="#fff">
<animate dur="1s" attributeName="offset" fill="freeze" from="1" to="0" />
</stop>
</linearGradient>
</defs>我在SVG标记中使用了以下代码来更改svg的填充,它可以正常工作。
fill="url(#left-to-right)"不过,我希望能够将填充内容从中更改为:
<linearGradient id="left-to-right">至:
<linearGradient id="right-to-left">(所以,从根本上改变这一点:
fill="url(#left-to-right)"要这样做:
fill="url(#right-to-left)")
有没有办法用Javascript来做这件事,反之亦然?(从“从右到左”回到“从左到右”)
发布于 2020-05-06 23:44:43
Yo可以使用document.getElementById()获取svg元素,然后使用Element.setAttribute方法更改其fill属性。
如果您还想在每次更改填充时重新启动动画,则可以编写如下代码:
document.querySelectorAll('animate').forEach(element => element.beginElement());document.querySelectorAll('animate')将查找所有带有<animate>标记的元素(请注意,animate之前没有点,所以它不是类名)。然后,对于它们中的每一个,您都调用.beginElement()来重新启动动画。有关说明,请查看SVGAnimationElement
function change() {
const rect = document.getElementById('rect');
const fill = rect.getAttribute('fill');
rect.setAttribute('fill', fill === 'url(#left-to-right)' ? 'url(#right-to-left)' : 'url(#left-to-right)');
document.querySelectorAll('animate').forEach(element => element.beginElement());
}<svg viewBox="0 0 40 40" width="40" height="40">
<defs>
<linearGradient id="left-to-right">
<stop offset="0" stop-color="#000000">
<animate dur="1s" attributeName="offset" fill="freeze" from="0" to="1" />
</stop>
<stop offset="0" stop-color="#fff">
<animate dur="1s" attributeName="offset" fill="freeze" from="0" to="1" />
</stop>
</linearGradient>
<linearGradient id="right-to-left">
<stop offset="0" stop-color="#000000">
<animate dur="1s" attributeName="offset" fill="freeze" from="1" to="0" />
</stop>
<stop offset="0" stop-color="#fff">
<animate dur="1s" attributeName="offset" fill="freeze" from="1" to="0" />
</stop>
</linearGradient>
</defs>
<rect id="rect" x="10" y="10" width="20" height="20" fill="url(#left-to-right)"></rect>
</svg>
<br>
<button onclick="change()">Change</button>
https://stackoverflow.com/questions/61638956
复制相似问题