img src SVG 使用 CSS 更改样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24933430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:46:22  来源:igfitidea点击:

img src SVG changing the styles with CSS

cssimagesvg

提问by ngplayground

html

html

<img src="logo.svg" alt="Logo" class="logo-img">

css

css

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

The above svg loads and is natively fill: #fffbut when I use the above cssto 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 加载并且是本机的,fill: #fff但是当我使用上面的css方法尝试将其更改为黑色时,它不会改变,这是我第一次使用 SVG,我不确定为什么它不起作用。

回答by Rowe Morehouse

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.svgin a text editor.

  2. look for fill: #fffand replace it with fill: #000

  1. logo.svg在文本编辑器中打开您的。

  2. 寻找fill: #fff并替换它fill: #000

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

例如,您logo.svg在文本编辑器中打开时可能如下所示:

<svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
  <path d="M0 0h24v24H0z" fill="none"/>
  <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z" fill="#fff"/>
</svg>

... just change the fill and save.

...只需更改填充并保存。

回答by André Kuhlmann

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

您可以将 svg 设置为掩码。这样设置背景颜色将作为您的填充颜色。

HTML

HTML

<div class="logo"></div>

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/
MDN:https://developer.mozilla.org/en-US/docs/Web/CSS/mask

JSFiddle:https
: //jsfiddle.net/KuhlTime/2j8exgcb/ MDN:https : //developer.mozilla.org/en-US/docs/Web/CSS/mask

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

请注意,此方法不适用于 Edge 浏览器。您可以访问此网站进行检查:https: //caniuse.com/#search=mask

回答by Feri

Try pure CSS:

尝试纯 CSS:

.logo-img {
  // to black
  filter: invert(1);
  // or to blue
  // filter: invert(1) sepia(1) saturate(5) hue-rotate(175deg);
}

more info in this article https://blog.union.io/code/2017/08/10/img-svg-fill/

本文中的更多信息https://blog.union.io/code/2017/08/10/img-svg-fill/

回答by northamerican

2018: If you want a dynamic color, do not want to use javascript and do not want an inline SVG, use a CSS variable. Works in Chrome, Firefox and Safari. edit: and Edge

2018 年:如果您想要动态颜色,不想使用 javascript 并且不想要内联 SVG,请使用 CSS 变量。适用于 Chrome、Firefox 和 Safari。编辑:和边缘

<svg>
    <use xlink:href="logo.svg" style="--color_fill: #000;"></use>
</svg>

In your SVG, replace any instances of style="fill: #000"with style="fill: var(--color_fill)".

在你的SVG,替换的任何实例style="fill: #000"style="fill: var(--color_fill)"

回答by Waruyama

You will first have to inject the SVG into the HTML DOM.

您首先必须将 SVG 注入到 HTML DOM 中。

There is an open source library called SVGInjectthat does this for you. It uses the onloadattribute to trigger the injection.

有一个名为SVGInject 的开源库可以为您执行此操作。它使用该onload属性来触发注入。

Here is a minimal example using SVGInject:

这是一个使用 SVGInject 的最小示例:

<html>
  <head>
    <script src="svg-inject.min.js"></script>
  </head>
  <body>
    <img src="image.svg" onload="SVGInject(this)" />
  </body>
</html>

After the image is loaded the onload="SVGInject(this)will trigger the injection and the <img>element will be replaced by the contents of the SVG file provided in the srcattribute.

加载图像后,onload="SVGInject(this)将触发注入,<img>元素将被src属性中提供的 SVG 文件的内容替换。

It solves several issues with SVG injection:

它解决了 SVG 注入的几个问题:

  1. SVGs can be hidden until injection has finished. This is important if a style is already applied during load time, which would otherwise cause a brief "unstyled content flash".

  2. The <img>elements inject themselves automatically. If you add SVGs dynamically, you don't have to worry about calling the injection function again.

  3. A random string is added to each ID in the SVG to avoid having the same ID multiple times in the document if an SVG is injected more than once.

  1. SVG 可以隐藏,直到注入完成。如果在加载期间已经应用了样式,这很重要,否则会导致短暂的“无样式内容闪烁”。

  2. <img>元素自动注入自己。如果动态添加SVG,就不用担心再次调用注入函数了。

  3. 如果 SVG 被多次注入,SVG 中的每个 ID 都会添加一个随机字符串,以避免在文档中多次出现相同的 ID。

SVGInject is plain Javascript and works with all browsers that support SVG.

SVGInject 是纯 Javascript,适用于所有支持 SVG 的浏览器。

Disclaimer: I am the co-author of SVGInject

免责声明:我是 SVGInject 的合著者

回答by Seb3736

This answer is based on answer https://stackoverflow.com/a/24933495/3890888but 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 svgto 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/

回答by gringo

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 color 属性更改字形的颜色?不需要javascript

回答by Matt Wujek

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

回答by JasperZelf

Use filters to transform to any color.

使用过滤器转换为任何颜色。

I recently found this solution, and hope somebody might be able to use it. Since the solution uses filters, it can be used with any type of image. Not just svg.

我最近找到了这个解决方案,希望有人可以使用它。由于该解决方案使用过滤器,因此它可以用于任何类型的图像。不仅仅是svg。

If you have a single-color image that you just want to change the color of, you can do this with the help of some filters. It works on multicolor images as well of course, but you can't target a specific color. Only the whole image.

如果您只想更改单色图像的颜色,则可以借助一些过滤器来完成此操作。它当然也适用于多色图像,但您不能针对特定颜色。只有整个图像。

The filters came from the script proposed in How to transform black into any given color using only CSS filtersIf you want to change white to any color, you can adjust the invert value in each filter.

过滤器来自如何仅使用 CSS 过滤器将黑色转换为任何给定颜色中提出的脚本 如果您想将白色更改为任何颜色,您可以调整每个过滤器中的反转值。

.startAsBlack{
  display: inline-block;
  width: 50px;
  height: 50px;
  background: black;
}

.black-green{
  filter: invert(43%) sepia(96%) saturate(1237%) hue-rotate(88deg) brightness(128%) contrast(119%);
}

.black-red{
  filter: invert(37%) sepia(93%) saturate(7471%) hue-rotate(356deg) brightness(91%) contrast(135%);
}

.black-blue{
  filter: invert(12%) sepia(83%) saturate(5841%) hue-rotate(244deg) brightness(87%) contrast(153%);
}

.black-purple{
  filter: invert(18%) sepia(98%) saturate(2657%) hue-rotate(289deg) brightness(121%) contrast(140%);
}
Black to any color: <br/>
<div class="startAsBlack black-green"></div>
<div class="startAsBlack black-red"></div>
<div class="startAsBlack black-blue"></div>
<div class="startAsBlack black-purple"></div>

回答by wcb1

If you are just switching the image between the real color and the black-and-white, you can set one selector as:

如果只是在真彩色和黑白之间切换图像,可以将一个选择器设置为:

{filter:none;}

{过滤器:无;}

and another as:

另一个为:

{filter:grayscale(100%);}