热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

imgsrcSVG改变填充颜色-imgsrcSVGchangingthefillcolor

htmlhtml<imgsrclogo.svgaltLogo>csscss.logo-imgpath{fill

html

html

Logo

css

css

.logo-img path {
  fill: #000;
}

The above svg loads and is natively fill: #fff but when I use the above css to try change it to black it doesn't change, this is my first time playing with SVG and I am not sure why it's not working.

上面的svg加载并自动填充:#fff,但是当我使用上面的css尝试将它改为黑色时,它不会改变,这是我第一次使用svg,我不确定为什么它不能工作。

10 个解决方案

#1


155  

You need to make the SVG to be an inline SVG. You can make use of this script, by adding a class svg to the image:

您需要使SVG成为内联的SVG。您可以使用这个脚本,向图像添加一个svg类:

/*
 * 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');

        // 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');

});

And then, now if you do:

然后,如果你做的事:

.logo-img path {
  fill: #000;
}

Or may be:

或者可能是:

.logo-img path {
  background-color: #000;
}

This works!

这个工作!

Fiddle: http://jsfiddle.net/wuSF7/462/

Credits for the above script: How to change color of SVG image using CSS (jQuery SVG image replacement)?

上述脚本的优点:如何使用CSS改变SVG图像的颜色(jQuery SVG图像替换)?

#2


72  

If your goal is just to change the color of the logo, and you don't necessarily NEED to use CSS, then don't use Javascript or jquery as was suggested by some previous answers.

如果您的目标只是更改徽标的颜色,并且您不必使用CSS,那么就不要使用Javascript或jquery,正如前面的一些答案所建议的那样。

To precisely answer the original question, just:

要准确地回答最初的问题,只需:

  1. Open your logo.svg in a text editor.

    打开你的标志。svg在文本编辑器中。

  2. look for fill: #fff and replace it with fill: #000

    寻找填补:# fff和替换它填补:# 000

For example, your logo.svg might look like this when opened in a text editor:

例如,您的标志。svg在文本编辑器中打开时可能是这样的:


  
  

... just change the fill and save.

…只需更改填充并保存。

#3


20  

You could set your svg as a mask. That way setting a background-color would act as your fill color.

您可以将svg设置为一个遮罩。这样设置背景颜色就可以作为填充颜色。

HTML

HTML


CSS

CSS

.logo {
    background-color: red;
    -webkit-mask: url(logo.svg) no-repeat center;
    mask: url(logo.svg) no-repeat center;
}

JSFiddle: https://jsfiddle.net/KuhlTime/2j8exgcb/

JSFiddle:https://jsfiddle.net/KuhlTime/2j8exgcb/

Please note that this method is not working for the Edge browser. You can check that by going to this website: https://caniuse.com/#search=mask

请注意,此方法不适用于边缘浏览器。你可以通过这个网站查看:https://caniuse.com/#search=mask。

#4


17  

The answer from @Praveen is solid.

@Praveen的答案是可靠的。

I couldn't get it to respond in my work, so I made a jquery hover function for it.

我无法让它在我的工作中响应,所以我为它制作了一个jquery悬浮函数。

CSS

CSS

.svg path {
   transition:0.3s all !important;
}

JS / JQuery

JS / JQuery

// code from above wrapped into a function
replaceSVG();

// hover function
// hover over an element, and find the SVG that you want to change
$('.element').hover(function() {
    var el = $(this);
    var svg = el.find('svg path');
    svg.attr('fill', '#CCC');
}, function() {
    var el = $(this);
    var svg = el.find('svg path');
    svg.attr('fill', '#3A3A3A');
});

#5


7  

Why not create a webfont with your svg image or images, import the webfont in the css and then just change the color of the glyph using the css color attribute? No Javascript needed

为什么不使用svg图像或图像创建webfont,在css中导入webfont,然后使用css颜色属性更改字形的颜色呢?不需要Javascript

#6


5  

This answer is based on answer https://stackoverflow.com/a/24933495/3890888 but with a plain Javascript version of the script used there.

这个答案基于以下答案:https://stackoverflow.com/a/24933495/3890888,但是使用的脚本的普通Javascript版本。

You need to make the SVG to be an inline SVG. You can make use of this script, by adding a class svg to the image:

您需要使SVG成为内联的SVG。您可以使用这个脚本,向图像添加一个svg类:

/*
 * Replace all SVG images with inline SVG
 */
document.querySelectorAll('img.svg').forEach(function(img){
    var imgID = img.id;
    var imgClass = img.className;
    var imgURL = img.src;

    fetch(imgURL).then(function(response) {
        return response.text();
    }).then(function(text){

        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(text, "text/xml");

        // Get the SVG tag, ignore the rest
        var svg = xmlDoc.getElementsByTagName('svg')[0];

        // Add replaced image's ID to the new SVG
        if(typeof imgID !== 'undefined') {
            svg.setAttribute('id', imgID);
        }
        // Add replaced image's classes to the new SVG
        if(typeof imgClass !== 'undefined') {
            svg.setAttribute('class', imgClass+' replaced-svg');
        }

        // Remove any invalid XML tags as per http://validator.w3.org
        svg.removeAttribute('xmlns:a');

        // Check if the viewport is set, if the viewport is not set the SVG wont't scale.
        if(!svg.getAttribute('viewBox') && svg.getAttribute('height') && svg.getAttribute('width')) {
            svg.setAttribute('viewBox', '0 0 ' + svg.getAttribute('height') + ' ' + svg.getAttribute('width'))
        }

        // Replace image with new SVG
        img.parentNode.replaceChild(svg, img);

    });

});

And then, now if you do:

然后,如果你这样做:

.logo-img path {
  fill: #000;
}

Or may be:

或者可能是:

.logo-img path {
  background-color: #000;
}

JSFiddle: http://jsfiddle.net/erxu0dzz/1/

JSFiddle:http://jsfiddle.net/erxu0dzz/1/

#7


5  

To expand on @gringo answer, the Javascript method described in other answers works, but requires the user to download unnecessary image files, and IMO, it bloats your code.

要扩展@gringo应答,其他答案中描述的Javascript方法可以工作,但是需要用户下载不必要的图像文件,而且在IMO上,它会使代码膨胀。

I think a better approach would be to to migrate all 1-color vector graphics to a webfont file. I've used Fort Awesome in the past, and it works great to combine your custom icons/images in SVG format, along with any 3rd party icons you may be using (Font Awesome, Bootstrap icons, etc.) into a single webfont file the user has to download. You can also customize it, so you only include the 3rd party icons you're using. This reduces the number of requests the page has to make, and you're overall page weight, especially if you're already including any 3rd party icons libraries.

我认为更好的方法是将所有的1色矢量图形迁移到webfont文件中。我以前使用过Fort Awesome,它可以很好地将定制的SVG格式的图标/图像与您可能使用的任何第三方图标(字体Awesome、引导图标等)结合到用户必须下载的单个webfont文件中。你也可以定制它,所以你只包括你正在使用的第三方图标。这减少了页面必须发出的请求的数量,并且减少了页面的总体权重,特别是如果已经包含了任何第三方图标库的话。

If you prefer a more dev oriented option, you could Google "npm svg webfont", and use one of the node modules that's most appropriate for your environment.

如果您更喜欢面向开发的选项,那么可以使用谷歌“npm svg webfont”,并使用最适合您的环境的节点模块之一。

Once, you've done either of those two options, then you could easily change the color via CSS, and most likely, you've sped up your site in the process.

有一次,您已经完成了这两个选项中的任何一个,然后您可以通过CSS轻松地更改颜色,而且很有可能,您已经加快了您的站点的进程。

#8


0  

If you have access to JQuery, then extending to Praveen's answer one can programatically change color of different nested elements inside SVG by:

如果您可以访问JQuery,那么扩展到Praveen的答案,您可以通过以下方式改变SVG内部不同嵌套元素的颜色:

$('svg').find('path, text').css('fill', '#ffffff');

美元(svg)。找到(道路、文本)。css(“填满”,“# ffffff”);

Within find, you can mention different elements that needs to be changed in color.

在find中,您可以提到需要更改颜色的不同元素。

#9


0  

The main problem in your case is that you are importing the svg from an tag which will hide the SVG structure.

在您的例子中,主要的问题是您正在从一个将隐藏svg结构的标记导入svg。

You need to use the tag in conjunction with the to get the desired effect. To make it work, you need to give an id to the path you want to use in the SVG file to then be able to retrieve them from the tag. Try the snipped below.

您需要将 标记与 一起使用,以获得所需的效果。要使它正常工作,您需要为SVG文件 标记中检索它们。试一试下面剪掉。

.icon {
  display: inline-block;
  width: 2em;
  height: 2em;
  transition: .5s;
  fill: currentColor;
  stroke-width: 5;
  }
  .icon:hover {
    fill: rgba(255,255,255,0);
    stroke: black;
    stroke-width: 2;
    }

.red {
  color: red;
  }

.blue {
  color: blue;
  }

  
    


  
  
          
            
          
        
  
    
          
            
          
        

Note that you can put any URL before the fragment # if you want to load the SVG from an external source (and not embed it into your HTML). Also, usually you do not specify the fill into the CSS. It's better to consider using fill:"currentColor" within the SVG itself. The corresponding element's CSS color value will then be used in place.

注意,如果想从外部源加载SVG(而不是将其嵌入到HTML中),则可以将任何URL放在片段#之前。此外,通常您不会在CSS中指定填充。最好考虑在SVG内部使用fill:“currentColor”。相应元素的CSS颜色值将被使用。

#10


0  

Since SVG is basically code, you need just contents. I used PHP to obtain content, but you can use whatever you want.

因为SVG基本上是代码,所以只需要内容。我使用PHP获取内容,但是您可以使用任何您想要的内容。


Then, I've printed content "as is" inside a div container

然后,我将内容“as is”打印到div容器中

To finnaly set rule to container's SVG childs on CSS

最后,在CSS中将规则设置为容器的SVG childs

.fill-class > svg { 
    fill: orange;
}

I got this results with a material icon SVG:

我用一个材质图标SVG得到了这个结果:

Mozilla Firefox 59.0.2 (64-bit) Linux

Mozilla Firefox 59.0.2(64位)Linux

enter image description here

Google Chrome66.0.3359.181 (Build oficial) (64 bits) Linux

谷歌Chrome66.0.3359.181(编译)(64位)Linux

enter image description here

Opera 53.0.2907.37 Linux

歌剧53.0.2907.37 Linux

enter image description here


推荐阅读
  • Android实战——jsoup实现网络爬虫,糗事百科项目的起步
    本文介绍了Android实战中使用jsoup实现网络爬虫的方法,以糗事百科项目为例。对于初学者来说,数据源的缺乏是做项目的最大烦恼之一。本文讲述了如何使用网络爬虫获取数据,并以糗事百科作为练手项目。同时,提到了使用jsoup需要结合前端基础知识,以及如果学过JS的话可以更轻松地使用该框架。 ... [详细]
  • Html5-Canvas实现简易的抽奖转盘效果
    本文介绍了如何使用Html5和Canvas标签来实现简易的抽奖转盘效果,同时使用了jQueryRotate.js旋转插件。文章中给出了主要的html和css代码,并展示了实现的基本效果。 ... [详细]
  • 本文介绍了如何在Jquery中通过元素的样式值获取元素,并将其赋值给一个变量。提供了5种解决方案供参考。 ... [详细]
  • 本文介绍了使用jQuery实现图片预加载和等比例缩放的方法,同时提供了演示和相关代码。该方法可以重置图片的宽度和高度,并使图片在水平和垂直方向上居中显示。 ... [详细]
  • 一篇文章搞定css3 3d效果
    css33d学习心得卡片反转魔方banner图首先我们要学习好css33d一定要有一定的立体感通过这个图片应该清楚的了解到了x轴y轴z轴是什么概念了。首先先给大家看一个小 ... [详细]
  • 这篇文章将为大家详细讲解有关如何使用JavaScript动态设置CSS3属性值,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读 ... [详细]
  • GetWindowLong函数
    今天在看一个代码里头写了GetWindowLong(hwnd,0),我当时就有点费解,靠,上网搜索函数原型说明,死活找不到第 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • Voicewo在线语音识别转换jQuery插件的特点和示例
    本文介绍了一款名为Voicewo的在线语音识别转换jQuery插件,该插件具有快速、架构、风格、扩展和兼容等特点,适合在互联网应用中使用。同时还提供了一个快速示例供开发人员参考。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • HTML5网页模板怎么加百度统计?
    本文介绍了如何在HTML5网页模板中加入百度统计,并对模板文件、css样式表、js插件库等内容进行了说明。同时还解答了关于HTML5网页模板的使用方法、表单提交、域名和空间的问题,并介绍了如何使用Visual Studio 2010创建HTML5模板。此外,还提到了使用Jquery编写美好的HTML5前端框架模板的方法,以及制作企业HTML5网站模板和支持HTML5的CMS。 ... [详细]
  • 本文介绍了Java后台Jsonp处理方法及其应用场景。首先解释了Jsonp是一个非官方的协议,它允许在服务器端通过Script tags返回至客户端,并通过javascript callback的形式实现跨域访问。然后介绍了JSON系统开发方法,它是一种面向数据结构的分析和设计方法,以活动为中心,将一连串的活动顺序组合成一个完整的工作进程。接着给出了一个客户端示例代码,使用了jQuery的ajax方法请求一个Jsonp数据。 ... [详细]
  • 本文介绍了DataTables插件的官方网站以及其基本特点和使用方法,包括分页处理、数据过滤、数据排序、数据类型检测、列宽度自动适应、CSS定制样式、隐藏列等功能。同时还介绍了其易用性、可扩展性和灵活性,以及国际化和动态创建表格的功能。此外,还提供了参数初始化和延迟加载的示例代码。 ... [详细]
  • angular.element使用方法及总结
    2019独角兽企业重金招聘Python工程师标准在线查询:http:each.sinaapp.comangularapielement.html使用方法 ... [详细]
  • 本文由编程笔记#小编为大家整理,主要介绍了css回到顶部按钮相关的知识,希望对你有一定的参考价值。 ... [详细]
author-avatar
chucai
这个家伙很懒,什么也没留下,只留下了这个默认个签!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有