首先,在HTML中使用img标签嵌入SVG图形。我使用Adobe Illustrator制作图形。
<img id="facebook-logo" class="svg social-link" src="/images/logo-facebook.svg"/>
就像您嵌入普通图像一样。请注意,您需要将IMG设置为具有svg类。’social-link’类仅出于示例目的。该ID不是必需的,但很有用。
然后使用此jQuery代码(在单独的文件中或HEAD中的内联中)。
/**
* 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');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
上面的代码所做的是查找所有带有“ svg”类的IMG,并将其替换为链接文件中的内联SVG。巨大的优势在于,它允许您现在使用CSS来更改SVG的颜色,如下所示:
svg:hover path {
fill: red;
}
我编写的jQuery代码还跨越了原始图像ID和类。因此,此CSS也适用:
#facebook-logo:hover path {
fill: red;
}
要么:
.social-link:hover path {
fill: red;
}