我可以更改什么';用javascript在svg元素的fill标记中的?

我可以更改什么';用javascript在svg元素的fill标记中的?,javascript,html,css,svg,Javascript,Html,Css,Svg,我在SVG的defs标记中有以下LinearGradient: 我在svg标记中使用以下内容来更改svg的填充,并且它工作正常 fill=“url(#从左到右)” 尽管如此,我希望能够从中更改填充: 致: (所以,基本上改变这一点: fill=“url(#从左到右)” 为此: fill=“url(#从右到左)” ) 有没有一种方法可以使用Javascript实现这一点,反之亦然?(从“从右到左”返回到“从左到右”)Yo可以使用document.getElementById()获

我在SVG的defs标记中有以下LinearGradient:


我在svg标记中使用以下内容来更改svg的填充,并且它工作正常

fill=“url(#从左到右)”
尽管如此,我希望能够从中更改填充:


致:


(所以,基本上改变这一点:

fill=“url(#从左到右)”
为此:

fill=“url(#从右到左)”
)


有没有一种方法可以使用Javascript实现这一点,反之亦然?(从“从右到左”返回到“从左到右”)

Yo可以使用
document.getElementById()
获取svg元素,然后使用方法更改其
fill
属性

如果还希望在每次更改填充时重新启动动画,可以编写如下内容:

document.querySelectorAll('animate').forEach(element => element.beginElement());
document.querySelectorAll('animate')
将找到所有包含

函数更改(){
const rect=document.getElementById('rect');
常量fill=rect.getAttribute('fill');
rect.setAttribute('fill',fill=='url(#从左到右)'url(#从右到左)'url(#从左到右)';
document.querySelectorAll('animate').forEach(element=>element.beginElement());
}



更改
尝试使用methodsetAttribute更简单,因为您不必传递初始的null参数。对不起,我是JS的新手,正在尝试理解您的code=P document.queryselectoral('animate').forEach(element=>element.beginElement())做什么?我找到了,但您没有在代码中的任何地方添加
class=“animate”
,它是否以
标记为目标?为什么?@xXnikosXx我在回答中添加了更多信息。简而言之,
querySelectorAll
使用。如果要按类名进行查询,可以编写
querySelectorAll('.class name')
(带点)。如果您不指定点,它将按标记名进行查询。我后来注意到您没有添加点=P。我唯一不明白的是
.forEach(element=>element.beginElement())但我正在读关于它的文章。谢谢你的帮助!!!