img src SVG改变填充颜色 [英] img src SVG changing the fill color
本文介绍了img src SVG改变填充颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
html
< img src =logo.svgalt =Logo class =logo-img>
css
.logo-img path {
fill:#000;
}
上面的svg加载并且原生 fill: fff
但是当我使用上面的 css
尝试改为黑色它不会改变,这是我第一次玩SVG和我
解决方案
您需要将SVG设为内联SVG 。您可以使用此脚本,通过向图像添加一个类 svg
:
/ *
*用inline SVG替换所有的SVG图片
* /
jQuery('img.svg')。each(function(){
var $ img = jQuery(this);
var imgID = $ img.attr('id');
var imgClass = $ img.attr('class');
var imgURL = $ img。 attr('src');
jQuery.get(imgURL,function(data){
//获取SVG标签,忽略其余的
var $ svg = jQuery数据).find('svg');
//将替换的图像的ID添加到新的SVG
if(typeof imgID!=='undefined'){
$ svg = $ svg.attr('id',imgID);
}
//将替换的图像类添加到新的SVG
if(typeof imgClass!=='undefined'){
$ svg = $ svg.attr('class',imgClass +'replaced-svg');
}
//根据http://验证器删除任何无效的XML标记。 w3.org
$ svg = $ svg.removeAttr('xmlns:a');
//检查视口是否设置,如果视口没有设置SVG不缩放。
if(!$ svg.attr('viewBox')&& $ svg.attr('height')&& $ svg.attr('width')){
$ svg .attr('viewBox','0 0'+ $ svg.attr('height')+''+ $ svg.attr('width'))
}
使用新的SVG替换图片
$ img.replaceWith($ svg);
},'xml');
})
然后,现在如果你这样做:
.logo-img path {
fill:#000;
}
或可能是:
.logo-img path {
background-color:#000;
}
这样就可以了!
< h3>小提琴: http://jsfiddle.net/wuSF7/462/
以上脚本的信用:如何使用CSS(jQuery SVG图像替换)更改SVG图像的颜色?
html
<img src="logo.svg" alt="Logo" class="logo-img">
css
.logo-img path {
fill: #000;
}
The above svg loads and is natively fill: #fff
but when I use the above css
to try change it to black it doesn't change, this is my first time playing with SVG and I am not sure why it's not working.
解决方案
You need to make the SVG to be an inline SVG. You can make use of this script, by adding a class svg
to the image:
/*
* Replace all SVG images with inline SVG
*/
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Check if the viewport is set, if the viewport is not set the SVG wont't scale.
if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
$svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
}
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
And then, now if you do:
.logo-img path {
fill: #000;
}
Or may be:
.logo-img path {
background-color: #000;
}
This works!
Fiddle: http://jsfiddle.net/wuSF7/462/
Credits for the above script: How to change color of SVG image using CSS (jQuery SVG image replacement)?
这篇关于img src SVG改变填充颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文