html 修改svg颜色,如何使用CSS(jQuerySVG图像替换)改变SVG图像的颜色?

首先,在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;}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值