• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在用作背景图像时修改 SVG 图像的填充颜色?

用户头像
it1352
帮助1

问题说明

将 SVG 输出直接与页面代码内联,我可以简单地使用 CSS 修改填充颜色,如下所示:

Placing the SVG output directly inline with the page code I am able to simply modify fill colors with CSS like so:

polygon.mystar {
    fill: blue;
}

circle.mycircle {
    fill: green;
}

这很好用,但是我正在寻找一种方法来修改作为背景图像的 SVG 的填充"属性.

This works great, however I'm looking for a way to modify the "fill" attribute of an SVG when it's being served as a BACKGROUND-IMAGE.

html {      
    background-image: url(../img/bg.svg);
}

我现在如何更改颜色?甚至有可能吗?

How can I change the colors now? Is it even possible?

作为参考,这里是我的外部 SVG 文件的内容:

For reference, here are the contents of my external SVG file:

<svg version="1.1"   xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         viewBox="0 0 320 100" enable-background="new 0 0 320 100" xml:space="preserve">
<polygon   fill="#3CB54A" points="134.973,14.204 143.295,31.066 161.903,33.77 148.438,46.896 151.617,65.43 134.973,56.679 
    118.329,65.43 121.507,46.896 108.042,33.77 126.65,31.066 "/>
<circle   fill="#ED1F24" cx="202.028" cy="58.342" r="12.26"/>
</svg>

正确答案

#1

我需要类似的东西并想坚持使用 CSS.这里有 LESS 和 SCSS mixin 以及可以帮助您解决此问题的普通 CSS.不幸的是,它的浏览器支持有点松懈.有关浏览器支持的详细信息,请参见下文.

I needed something similar and wanted to stick with CSS. Here are LESS and SCSS mixins as well as plain CSS that can help you with this. Unfortunately, it's browser support is a bit lax. See below for details on browser support.

少混入:

.element-color(@color) {
  background-image: url('data:image/svg xml;utf8,<svg ...><g stroke="@{color}" ... /></g></svg>');
}

较少使用:

.element-color(#fff);

<小时>

SCSS 混合:


SCSS mixin:

@mixin element-color($color) {
  background-image: url('data:image/svg xml;utf8,<svg ...><g stroke="#{$color}" ... /></g></svg>');
}

SCSS 用法:

@include element-color(#fff);

<小时>

CSS:


CSS:

// color: red
background-image: url('data:image/svg xml;utf8,<svg ...><g stroke="red" ... /></g></svg>');

<小时>

这里有更多关于将完整 SVG 代码嵌入到 CSS 中的信息文件.它还提到了浏览器兼容性,这有点太小,无法成为一个可行的选择.


Here is more info on embedding the full SVG code into your CSS file. It also mentioned browser compatibility which is a bit too small for this to be a viable option.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfihbg
系列文章
更多 icon
同类精品
更多 icon
继续加载