这是我提出的一段方便的代码的自我问答。

目前,还没有一种简单的方法来嵌入SVG图像,然后通过CSS访问SVG元素。使用JS SVG框架有多种方法,但如果您所做的只是制作一个带有翻转状态的简单图标,那么这些方法就过于复杂了。

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

问题是这样的:

我如何在CSS中嵌入SVG并改变其颜色而不使用JS-SVG框架?


当前回答

或者你可以使用CSS蒙版,授予浏览器的支持不是很好,但你可以使用一个备用

.frame {
    background: blue;
    -webkit-mask: url(image.svg) center / contain no-repeat;
}

其他回答

或者你可以使用CSS蒙版,授予浏览器的支持不是很好,但你可以使用一个备用

.frame {
    background: blue;
    -webkit-mask: url(image.svg) center / contain no-repeat;
}

如果可以在页面中包含文件(PHP include或通过您选择的CMS包含),则可以添加SVG代码并将其包含到页面中。这与将SVG源粘贴到页面相同,但使页面标记更清晰。

这样做的好处是,您可以通过CSS将SVG的某些部分用于悬停—不需要javascript。

http://codepen.io/chriscoyier/pen/evcBu

你只需要使用这样的CSS规则:

#pathidorclass:hover { fill: #303 !important; }

注意!important位是覆盖填充颜色所必需的。

我知道你想用CSS来完成这个,但只是一个提醒,以防它是一个小的,简单的图像-你可以随时在notepad++中弹出它,并更改路径/whatever元素的填充:

<path style="fill:#010002;" d="M394.854,205.444c9.218-15.461,19.102-30.181,14.258-49.527
    ...
    C412.843,226.163,402.511,211.451,394.854,205.444z"/>

这样可以节省大量难看的脚本。很抱歉,如果它偏离了基础,但有时简单的解决方案可能会被忽视。

...即使交换多个SVG图像也可能比这个问题的一些代码片段更小。

这是一个没有框架的代码,只有纯js:

document.querySelectorAll('img.svg').forEach(function(element) {
            var imgID = element.getAttribute('id')
            var imgClass = element.getAttribute('class')
            var imgURL = element.getAttribute('src')

            xhr = new XMLHttpRequest()
            xhr.onreadystatechange = function() {
                if(xhr.readyState == 4 && xhr.status == 200) {
                    var svg = xhr.responseXML.getElementsByTagName('svg')[0];

                    if(imgID != null) {
                         svg.setAttribute('id', imgID);
                    }

                    if(imgClass != null) {
                         svg.setAttribute('class', imgClass + ' replaced-svg');
                    }

                    svg.removeAttribute('xmlns:a')

                    if(!svg.hasAttribute('viewBox') && svg.hasAttribute('height') && svg.hasAttribute('width')) {
                        svg.setAttribute('viewBox', '0 0 ' + svg.getAttribute('height') + ' ' + svg.getAttribute('width'))
                    }
                    element.parentElement.replaceChild(svg, element)
                }
            }
            xhr.open('GET', imgURL, true)
            xhr.send(null)
        })

我用AngularJS写了一个指令来解决这个问题。它可在这里- ngReusableSvg。

它在SVG元素被呈现后替换它,并将其放置在div元素中,使其CSS易于更改。这有助于在不同的地方使用相同的SVG文件,使用不同的大小/颜色。

用法很简单:

<object oa-reusable-svg
        data="my_icon.svg"
        type="image/svg+xml"
        class="svg-class"
        height="30"  // given to prevent UI glitches at switch time
        width="30">
</object>

之后,你就可以轻松地拥有:

.svg-class svg {
    fill: red; // whichever color you want
}