我想使用这种技术并更改SVG颜色,但到目前为止我还不能这样做。我在CSS中使用这个,但我的图像总是黑色的,无论如何。

我的代码:

.change-my-color { 填充:绿色; } svg < > <image class="change-my-color" xlink:href="https://svgur.com/i/AFM.svg" width="96" height="96" src=" ppngback .png" /> < / svg >


当前回答

我发现它有点笨拙,但它绝对是一种动态改变<img>标记中包含的SVG颜色的工作方式。

在SVG文件中,您可以通过以下方式添加CSS内容:

<svg ...>
    <defs>
        <style>
            ...
        <style>
    <defs>

在这里可以使用@media规则,SVG可以使用该规则查看自身以外的上下文环境。有一个宽高比媒体特性应用于SVG框(例如,<img>标记)。您可以通过稍微拉伸SVG框来为SVG创建不同的上下文。

通过这种方式,您还可以使favicon与网站上出现的SVG相同,但使用不同的颜色。(在这种情况下,其他SVG框不应该是方形的。)

/* img stretched horizontally (if SVG is square-shaped) */
@media (min-aspect-ratio: 1000/999) {
    path {
        fill: blue;
    }
}

/* img stretched vertically (if SVG is square-shaped) */
@media (max-aspect-ratio: 999/1000) {
    path {
        fill: green;
    }
}

/* img with exact sizes */
@media (aspect-ratio: 86/74) {
    path {
        fill: red;
    }
}

/* favicon with light browser theme */
@media (aspect-ratio: 1/1) and (prefers-color-scheme: light) {
    path {
        fill: black;
    }
}

/* favicon with dark browser theme */
@media (aspect-ratio: 1/1) and (prefers-color-scheme: dark) {
    path {
        fill: white;
    }
}

有一点很重要

SVG必须包含viewBox信息,这样拉伸就不会影响图形。例子:

<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300" viewBox="0 0 300 300">

其他回答

最简单的技巧是在页面加载时使用jQuery改变颜色。

      $(document).ready(function () { 
              $('svg').find('path').attr('fill', '#FFF');
      });

#FFF是你想要设置的颜色代码。

简单地改变SVG文件的颜色:

转到SVG文件,在styles下面,在fill中提到颜色:

<style>.cls-1{fill: #FFFFFF;}</style>

我添加了一个测试页面-通过滤镜设置为SVG着色:

例如,

滤镜:反色(0.5)棕色(1)饱和(5)色相旋转(175度)

上传和着色您的SVG - Jsfiddle

我的想法来自:在图像标签SVGs上交换填充颜色

如果你想对一个内联SVG文件这样做,也就是说,例如,CSS内容中的背景图像:

背景:url(“数据:photo /svg+xml;charset=utf8,%3Csvg xml ='http://www.w3.org/2000/svg' fill='rgba(1.39,215.1)' viewBox=' ..3e % %3C/svg%3E’);

当然,替换…使用您的内联图像代码。

Manish Menaria的回答有一些问题,如果我们转换白色,它会显示灰色。

所以我添加了一些调整,下面的例子特别展示了如何改变材质图标的颜色:

<mat-icon class="draft-white" svgIcon="draft" aria-hidden="false"></mat-icon>
.draft-white{
    filter: brightness(0) invert(1);
}