且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 CSS(jQuery SVG 图像替换)更改 SVG 图像的颜色?

更新时间:2022-11-15 09:46:04

首先,在 HTML 中使用 IMG 标签来嵌入 SVG 图形.我使用 Adob​​e Illustrator 制作图形.

Firstly, use an IMG tag in your HTML to embed an SVG graphic. I used Adobe Illustrator to make the graphic.

<img id="facebook-logo" class="svg social-link" src="/images/logo-facebook.svg"/>

这就像您嵌入普通图像的方式.请注意,您需要将 IMG 设置为具有 svg 类.'social-link' 类只是为了举例.ID 不是必需的,但很有用.

This is just like how you'd embed a normal image. Note that you need to set the IMG to have a class of svg. The 'social-link' class is just for examples sake. The ID is not required, but is useful.

然后使用此 jQuery 代码(在单独的文件中或在 HEAD 中内联).

Then use this jQuery code (in a separate file or inline in the HEAD).

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

                // Replace image with new SVG
                $img.replaceWith($svg);

            }, 'xml');

        });

以上代码的作用是查找所有带有svg"类的 IMG,并将其替换为链接文件中的内联 SVG.巨大的优势是它允许您现在使用 CSS 来更改 SVG 的颜色,如下所示:

What the above code does is look for all IMG's with the class 'svg' and replace it with the inline SVG from the linked file. The massive advantage is that it allows you to use CSS to change the color of the SVG now, like so:

svg:hover path {
    fill: red;
}

我编写的 jQuery 代码还移植了原始图像 ID 和类.所以这个 CSS 也有效:

The jQuery code I wrote also ports across the original images ID and classes. So this CSS works too:

#facebook-logo:hover path {
    fill: red;
}

或者:

.social-link:hover path {
    fill: red;
}

您可以在这里看到它的工作示例:http://labs.funkhausdesign.com/examples/img-svg/img-to-svg.html

我们有一个更复杂的版本,包括缓存:https://github.com/funkhaus/style-guide/blob/master/template/js/site.js#L32-L90