您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

如何使用CSS更改SVG图像的颜色(jQuery 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;
}
CSS 2022/1/1 18:22:06 有278人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶