簡體   English   中英

如何使用CSS更改.svg圖像的顏色?

[英]How to change the color of an .svg image using css?

我正在使用Sass和.svg格式的圖像,正在使用它們,就好像它們是.jpg(或任何其他)圖像。

這是圖標(捕獲): 圖標.jpg

我想知道如何制作它,以便可以使用CSS改變顏色?

我正在使用.svg圖像,如下所示:

 .text::before { content: " "; display: block; background: url("./../Iconos/Icono\\ some-icon.svg"); background-repeat: no-repeat; background-position: center; cursor: pointer; width: 35px; height: 35px; float: right; } 
 <div class="text"> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Doloribus assumenda error reiciendis soluta rerum corporis, illo aspernatur laboriosam accusamus nisi fugiat amet possimus cumque eum id enim dolor repudiandae expedita.</p> </div> 

如果您這樣使用,將無法更改顏色,可以在html中使用更好的顏色,

<img src="image.svg" /> 

並在代碼中轉換svg img以便可以訪問svg路徑並在CSS中進行修改

 svg path {
    fill: #783cbc;
}

您可以在javascript中使用此功能進行轉換

  $('img.svg').each(function(){
         var $img = jQuery(this);
         var imgID = $img.attr('id');
         var imgClass = $img.attr('class');
         var imgURL = $img.attr('src');

         $.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');

      });

但是也許您想做的就是用圖標制作字體,以便輕松更改顏色,在這種情況下,有幾種選擇,您可以使用https://icomoon.io/進行操作,或者使用grunt可以使用https://github.com/sapegin/grunt-webfont

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM