首先,在HTML中使用IMG标记嵌入SVG图形。我用AdobeIlluStrator制作了这个图形。
这就像你如何嵌入一个正常的图像。请注意,您需要将IMG设置为有一个SVG类。“社交链接”类只是为了举例。ID不是必需的,但很有用。
然后使用以下jQuery代码(在单独的文件中或在头中的内联中)。/*
* 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;}