html
<img src="logo.svg" alt="Logo" class="logo-img">
css
.logo-img path {
fill: #000;
}
上面的svg加载并本机填充:#fff,但当我使用上面的css尝试将其更改为黑色时,它没有改变,这是我第一次使用svg,我不知道为什么它不工作。
html
<img src="logo.svg" alt="Logo" class="logo-img">
css
.logo-img path {
fill: #000;
}
上面的svg加载并本机填充:#fff,但当我使用上面的css尝试将其更改为黑色时,它没有改变,这是我第一次使用svg,我不知道为什么它不工作。
当前回答
为什么不创建一个webfont与您的svg图像或图像,导入webfont在css,然后只是改变字形的颜色使用css的颜色属性? 不需要javascript
其他回答
如果你想要一个动态的颜色,不想使用javascript,也不想使用内联SVG,使用CSS变量。适用于Chrome, Firefox和Safari。编辑:和Edge
<svg>
<use href="logo.svg" style="--color_fill: #000;"></use>
</svg>
在SVG中,将style="fill: #000"的任何实例替换为style="fill: var(——color_fill)"。
尝试纯CSS:
.logo-img {
/* to black */
filter: invert(1);
/* or to blue */
filter: invert(0.5) sepia(1) saturate(5) hue-rotate(175deg);
}
更多信息请参见本文https://blog.union.io/code/2017/08/10/img-svg-fill/
编辑您的SVG文件,将fill="currentColor"添加到SVG标记中,并确保从文件中删除任何其他填充属性。
例如:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 139.435269383854" id="img" fill="currentColor">...
</svg>
注意,currentColor是一个关键字(不是使用的固定颜色)。
在此之后,您可以使用CSS更改颜色,通过设置元素的颜色属性或从它的父元素。
例子:
.div-with-svg-inside {
color: red;
}
我忘了说,你必须这样插入SVG:
<svg>
<use xlink:href='/assets/file.svg#img' href="/assets/file.svg#img"></use>
</svg>
如果image来自某个变量,那么
<svg>
<use [attr.xlink:href]="somevariable + '#img'" [attr.href]="somevariable + '#img'"></use>
</svg>
Note that `#img` is the id of the `svg` tag inside svg file. Also note `xlink:href` has been deprecated instead you should use `href` or use can use both to support older browser versions.
Another way of doing it: [https://css-tricks.com/cascading-svg-fill-color/][1]
[1]: https://css-tricks.com/cascading-svg-fill-color/
如果你只是在真实颜色和黑白之间切换图像,你可以设置一个选择器为:
{过滤器:没有;}
另一个是:
{filter:grayscale(100%);}
来自@Praveen的答案是可靠的。
我不能让它在我的工作中响应,所以我为它做了一个jquery悬停函数。
CSS
.svg path {
transition:0.3s all !important;
}
JS / JQuery
// code from above wrapped into a function
replaceSVG();
// hover function
// hover over an element, and find the SVG that you want to change
$('.element').hover(function() {
var el = $(this);
var svg = el.find('svg path');
svg.attr('fill', '#CCC');
}, function() {
var el = $(this);
var svg = el.find('svg path');
svg.attr('fill', '#3A3A3A');
});