简体   繁体   English

使用Java脚本更改SVG的颜色

[英]Changing the colour of an SVG using Javascript

I am trying to figure out when I click my "center" and "right" container the colour of my .SVG changes to red (from white). 我想弄清楚当我单击“中”和“右”容器时,.SVG的颜色变为红色(从白色)。

My current html is: 我当前的html是:

<nav>
        <span class="nav-btn"> <img src="nav-icon.svg" style="width: 60px;height: 60px;"></span>
        <ul class="nav">
            <li><a href="#">Home</a></li>
            <li><a href="#">Prices</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </nav>

<div class="container" id= "left" >
        <h1 style="color:white"><a>HAIR</a></h1>
    </div>

    <div class= "container" id= "center">
        <h1 style="color:white"><a>BEAUTY<a/></h1>
    </div>

    <div class="container" id= "right">
        <h1 style="color:white"><a>BARBERS</a></h1>
    </div>
</div>

As far as I'm aware, you need to make the SVG inline to be able to style like this. 据我所知,您需要使SVG内联,以便能够进行这种样式设置。 Once the SVG is inline, you can use the "fill" style to change the colour. SVG内联后,您可以使用“填充”样式来更改颜色。

A dupe question has been answered here: 在这里回答了一个重复问题:

img src SVG changing the fill color img src SVG更改填充颜色

If the SVG image is transparent, it should be possible by simply setting it's background color to red. 如果SVG图像是透明的,则只需将其背景色设置为红色即可。 First you need to add an ID attribute to your img tag: 首先,您需要向img标签添加ID属性:

<img src="nav-icon.svg" id=mysvg ...>

Then you add onClick event to your center and right containers, like this: 然后,将onClick事件添加到中心容器和正确的容器中,如下所示:

 <div class= "container" id= "center" onClick="$('#mysvg').css('background-color','red')">

However if your svg is not transparent, you will need to load the SVG differently - do not put it in a separate file nav-icon.svg, but include it in the HTML itself as a set of tags, simply paste the contents of the svg file directly to the HTML, starting with the <svg> tag ... And then either modify the background directly in the code, or style the appropriate tag inside svg. 但是,如果您的svg不透明,则需要以不同的方式加载SVG-请勿将其放在单独的文件nav-icon.svg中,而应将其作为HTML标签本身包含在一组标签中,只需粘贴svg文件直接从<svg>标记开始到HTML。然后直接在代码中修改背景,或在svg内设置适当的标记样式。

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

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