css - 使用 SVG 图标

标签 css svg

我正在使用我自己的 SVG 图标,我正在尝试找到使用它们的最佳方式。

我想保留颜色,但如果需要匹配主题或在使用悬停时调整它。

我曾尝试使用以下脚本将以下内容更改为嵌入式 SVG,但是当我在 HTML 文档底部加载我的脚本时,我得到了可怕的跳跃效果。

$(function(){
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, else we gonna set it if we can.
        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');

});
});
svg {width: 350px; height: 350px;}
svg path {fill: #000 !important;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://upload.wikimedia.org/wikipedia/commons/f/f8/Windows_logo_-_2012_%28red%29.svg" alt="Microsoft" width="350" />

然后我尝试通过从 Illustrator 复制代码来嵌入 SVG,但我可以编辑颜色的唯一方法是在 html 文档中删除它们,因为我的 css 不会覆盖它们。

防止它们跳跃的最佳方法是什么?

最佳答案

内联 SVG 将是最好的 IMO。

使用 Illustrator 导出您的 SVG(如果您遇到问题,请按照 Colin Lord 的 excellent guide 进行操作)。

然后从您的 SVG 代码中删除颜色并仅使用 CSS 设置它们。 如果您无法覆盖您的颜色,您可以提供您的 SVG ID 以获得更多的特异性。

关于css - 使用 SVG 图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55221468/

相关文章:

javascript - 创建一个带有背景图片的 Javascript 画廊

javascript - 通过javascript获取SVG图形的大小

html - 当网页 url 在 localhost 中时上路径

CSS 在 div 中将文本与其他元素居中

javascript - 用于将更高的内联 block div 放入其容器行的 jQuery 选择器

javascript - 如何在 HTML 文件中使用 svg 突出显示整个 map ?

javascript - 如何使用 SnapSVG 将 SVG 作为树结构进行遍历?

javascript - Canvas 另存为图像 [canvg - 在 Canvas 上渲染 svg]

svg - SVG 符号中的线性渐变

javascript - 实现 javascript 倒计时时,其他 html 元素消失