讓用 img 嵌入的 svg 可以變色

最近覺得 SVG 很好用,在這個解析度非常多元的世代裡,靠 SVG 就可以做各種圖樣加上放大縮小都不會失真真的很方便,而且還可以用 HTML 的 img 標籤嵌入,但用 img 嵌入後就無法直接用 css 控制顏色,所以想要直接用 CSS 控制的話可以用加的 jQuery,就可以輕鬆愉快地控制了。

  1. jQuery('img.svg').each(function(){   
  2.     var $img = jQuery(this);   
  3.     var imgID = $img.attr('id');   
  4.     var imgClass = $img.attr('class');   
  5.     var imgURL = $img.attr('src');   
  6.   
  7.     jQuery.get(imgURL, function(data) {   
  8.         // Get the SVG tag, ignore the rest   
  9.         var $svg = jQuery(data).find('svg');   
  10.   
  11.         // Add replaced image's ID to the new SVG   
  12.         if(typeof imgID !== 'undefined') {   
  13.             $svg = $svg.attr('id', imgID);   
  14.         }   
  15.         // Add replaced image's classes to the new SVG   
  16.         if(typeof imgClass !== 'undefined') {   
  17.             $svg = $svg.attr('class', imgClass+' replaced-svg');   
  18.         }   
  19.   
  20.         // Remove any invalid XML tags as per http://validator.w3.org   
  21.         $svg = $svg.removeAttr('xmlns:a');   
  22.   
  23.         // Check if the viewport is set, if the viewport is not set the SVG wont't scale.   
  24.         if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {   
  25.             $svg.attr('viewBox''0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))   
  26.         }   
  27.   
  28.         // Replace image with new SVG   
  29.         $img.replaceWith($svg);   
  30.   
  31.     }, 'xml');   
  32.   
  33. });  

加了這段後,就可以直接用 CSS 控制顏色。

  1. <img class="svg icon" src="svg/favorite.svg" alt="favorite">  

  1. .icon{   
  2.     cursorpointer;   
  3. }   
  4. .icon:hover path{   
  5.     fill: #de5b78;   
  6. }  

記得控制 svg 填色是用 fill 就好了。

留言