填充外部导入的 svg 文件



我正在使用 Angular 5,我会填充我的白色 svg 图像。

我有一个这样的 svg 文件:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><title>ic_calendar</title><g id="Level_2" data-name="Level 2"><g id="screen"><path d="M18.5,5.11a2.55,2.55,0,0,0-.58-1.68,2.27,2.27,0,0,0-1.7-.71H14.85v-1a.68.68,0,1,0-1.35,0v1H6.39v-1A.67.67,0,0,0,5.72,1,.68.68,0,0,0,5,1.68v1H3.75A2.15,2.15,0,0,0,1.5,5.09V16.4a2.71,2.71,0,0,0,.69,2A2.08,2.08,0,0,0,3.7,19H16.34a2.14,2.14,0,0,0,2.15-2.26C18.51,15.07,18.5,5.57,18.5,5.11Zm-15.65,0h0c0-.71.27-1,.9-1H5v1a.69.69,0,0,0,.68.68.68.68,0,0,0,.67-.68v-1H13.5v1a.68.68,0,1,0,1.35,0v-1H16.2a1,1,0,0,1,.71.26,1.17,1.17,0,0,1,.24.72V6.84H2.85Zm14.3,11.64c0,.78-.52.9-.81.91H3.7a.73.73,0,0,1-.56-.2,1.49,1.49,0,0,1-.29-1V8.2h14.3Z" style="fill:#fff"/><rect width="20" height="20" style="fill:none"/></g></g></svg>

因此,我通过以下代码导入它:

<svg class="myClass">
<use xlink:href="assetFolder/ic_calendar.svg#Level_2"></use>
</svg>

但是,我无法更改 svg 图像样式,也无法填充它。我试图通过 sass,添加以下内容:

svg { fill: blue; }

path { fill: blue; }

但是什么都没有...谁能帮我?

谢谢

  • 表示属性svg具有最高优先级,不能随css更改。因此,如果您想要更改外部表中svg对象的颜色 CSS
  • 使用 <use> 命令时,svg对象落入shadow DOM
  • 为了设置这些对象的样式,必须使用强制继承

    path { fill:inherit; stroke:inherit; }

下面是一个示例,其中使用 use 命令从 <defs> 部分调用对象,并从外部表css

  path {
 fill:inherit;
stroke:inherit;
 }
 #screen {
  fill:dodgerblue;
 }
 rect {fill:#D5D5D5;}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<title>ic_calendar</title>
<defs>
<g id="screen">
<rect id="rect1" width="20" height="20"  />
<path  d="M18.5,5.11a2.55,2.55,0,0,0-.58-1.68,2.27,2.27,0,0,0-1.7-.71H14.85v-1a.68.68,0,1,0-1.35,0v1H6.39v-1A.67.67,0,0,0,5.72,1,.68.68,0,0,0,5,1.68v1H3.75A2.15,2.15,0,0,0,1.5,5.09V16.4a2.71,2.71,0,0,0,.69,2A2.08,2.08,0,0,0,3.7,19H16.34a2.14,2.14,0,0,0,2.15-2.26C18.51,15.07,18.5,5.57,18.5,5.11Zm-15.65,0h0c0-.71.27-1,.9-1H5v1a.69.69,0,0,0,.68.68.68.68,0,0,0,.67-.68v-1H13.5v1a.68.68,0,1,0,1.35,0v-1H16.2a1,1,0,0,1,.71.26,1.17,1.17,0,0,1,.24.72V6.84H2.85Zm14.3,11.64c0,.78-.52.9-.81.91H3.7a.73.73,0,0,1-.56-.2,1.49,1.49,0,0,1-.29-1V8.2h14.3Z"  />
</g>
</defs> 
<use xlink:href="#screen" />
</svg> 

您的 svg 路径上有一个内联样式 - style="fill:#fff" .内联样式优先于 CSS 样式表中的样式。但这就是!important的目的!

将您的样式更新为:

path { fill: blue !important; }

或者干脆删除内联样式。

最新更新