使用SVG图标

时间:2019-03-18 12:31:45

标签: css svg

我正在使用自己的SVG图标,并试图找到使用它们的最佳方法。

我想保留颜色,但如果需要匹配主题或使用鼠标悬停时也要调整颜色。

我尝试使用以下脚本将以下内容更改为嵌入式SVG,但是当我将脚本加载到HTML文档的底部时,我得到了可怕的跳跃效果。

ExternalIP
$(function(){
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');

        // Check if the viewport is set, else we gonna set it if we can.
        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');

});
});
svg {width: 350px; height: 350px;}
svg path {fill: #000 !important;}

然后我尝试通过从Illustrator复制代码来嵌入SVG,但是我可以编辑颜色的唯一方法是,如果将它们删除到html文档中,因为CSS不会覆盖它们。

阻止它们跳跃的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

内联SVG将是最好的IMO。

使用Illustrator导出SVG(如果遇到问题,请遵循Colin Lord的excellent guide)。

然后从SVG代码中删除颜色,并仅使用CSS进行设置。 如果您无法覆盖颜色,则可以提供SVG ID,以提高特异性。

答案 1 :(得分:0)

如果您采用嵌入式路由(这是我的首选),则实际上并不需要Illustrator通常抛出的大多数HTML。

这里是使用最少代码的SVG示例,然后您可以使用CSS更改颜色:-)

svg {
  width: 350px;
  height: 350px;
}

svg path {
  fill: #000;
  transform-origin: 0 0;
  transform: scale(3)
}

#svg3 path {
fill: turquoise;
}

#svg3:hover path {
fill: green;
}
<svg id="svg2">
  <path d="m0,12.402,35.687-4.8602,0.0156,34.423-35.67,0.20313zm35.67,33.529,0.0277,34.453-35.67-4.9041-0.002-29.78zm4.3261-39.025,47.318-6.906,0,41.527-47.318,0.37565zm47.329,39.349-0.0111,41.34-47.318-6.6784-0.0663-34.739z" id="path4"/>
</svg>


<!-- Another exmaple below using CSS to change the colours -->
<svg id="svg3">
  <path d="m0,12.402,35.687-4.8602,0.0156,34.423-35.67,0.20313zm35.67,33.529,0.0277,34.453-35.67-4.9041-0.002-29.78zm4.3261-39.025,47.318-6.906,0,41.527-47.318,0.37565zm47.329,39.349-0.0111,41.34-47.318-6.6784-0.0663-34.739z" id="path4"/>
</svg>

相关问题