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

德鲁·贝克

这是我想出的一小段代码的自我问答。

当前,没有简单的方法可以嵌入SVG图像,然后可以通过CSS访问SVG元素。有多种使用JS SVG框架的方法,但是如果您要做的只是制作带有过渡状态的简单图标,它们将过于复杂。

所以这就是我想出的,我认为这是迄今为止在网站上使用SVG文件的最简单方法。它的概念来自早期的文本到图像替换方法,但据我所知,从未对SVG进行过处理。

这是问题:

如何在不使用JS-SVG框架的情况下在SVG中嵌入SVG并更改其颜色?

德鲁·贝克

首先,在HTML中使用IMG标签嵌入SVG图形。我使用Adobe Illustrator制作图形。

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

就像嵌入普通图像一样。请注意,您需要将IMG设置为具有svg类。'social-link'类仅出于示例目的。该ID不是必需的,但很有用。

然后使用此jQuery代码(在单独的文件中或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的颜色,如下所示:

svg:hover path {
    fill: red;
}

我编写的jQuery代码还跨越了原始图像ID和类。因此,此CSS也适用:

#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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章