简体   繁体   English

如何更改使用链接的 svg 的填充<object> HTML 中的标签?

[英]How to change fill of svg which is linked using <object> tag in HTML?

I have an HTML file in which I have linked an svg object:我有一个HTML 文件,其中链接了一个 svg 对象:

<object id="svgGlasses" type="image/svg+xml" data="images/glasses.svg"></object>

and glasses.svg as followsglass.svg如下

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 width="42.604px" height="42.604px" viewBox="0 0 42.604 42.604" style="enable-background:new 0 0 42.604 42.604;"
 xml:space="preserve"> 
    <style type="text/css">
    <![CDATA[
        .circle{fill:#FAED24;}
    ]]>
    </style>
    <g id="Circle">
        <circle id="svgInternalID" class="circle" cx="21.302" cy="21.302" r="19.802"/>
    </g>
</svg>

When the user clicks on a button, which is in the HTML somewhere, I want the color of the circle to change to black.当用户单击某个位于 HTML 中的按钮时,我希望圆圈的颜色变为黑色。

I researched and found this JS, which I also added to the HTML, but it didn't work我研究并发现了这个 JS,我也将其添加到 HTML 中,但它不起作用

var Head= document.getElementById("svgGlasses").contentDocument();
Head = Head.getElementById("svgInternalID");
Head.style.setProperty("fill","color", "#ff0000");

Is there any way to do it without using inline svg有没有办法不使用内联 svg 来做到这一点

Yes you can do it without inline SVG and you're pretty close to the right answer already.是的,您可以在没有内联 SVG 的情况下做到这一点,并且您已经非常接近正确的答案了。

You've the arguments in the wrong place for setProperty.您在 setProperty 的错误位置设置了参数。 This works for me:这对我有用:

var Head= document.getElementById("svgGlasses").contentDocument();
Head = Head.getElementById("svgInternalID");
Head.style.setProperty("fill","#000000", "");

The colour you want to set should be the second argument.您要设置的颜色应该是第二个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM