Applying CSS to img-tag-embedded SVG images

2019-08-08 20:00发布

On my page I'm using the img tag to embed SVG images. Now I wanted to apply some css onto them. This works well as long as you copypaste the SVG source code directly into your page. However, if I embed them using the img src attribute, it doesn't.

Is there a way to make that work?

<style type="text/css">
path:hover {
    fill:white;
}
</style>

<img src="my.svg" />

Thanks in advance!

标签: html css svg
2条回答
欢心
2楼-- · 2019-08-08 20:35

Well it can be achieved through JQuery ( Work Around ) , this Jquery function will convert <img> tag that hold current svg image into a <svg> inline tags, you can view it in your browser debugger.In short it will mimic as if directly inserted the SVG image.

<script type="text/javascript">

    $(document).ready(function() {
        $('#img').each(function(){
            var img         = $(this);
            var image_uri   = img.attr('src');

            $.get(image_uri, function(data) {
                var svg = $(data).find('svg');
                svg.removeAttr('xmlns:a');
                img.replaceWith(svg);
            }, 'xml');

        });
    });
</script>


<img id='img' src="my.svg" />
查看更多
Evening l夕情丶
3楼-- · 2019-08-08 20:42

I do not think this is possible. You are correct in that using inline-SVG will allow you to manipulate the parts of the svg, but including it in an img tag will not. See http://css-tricks.com/using-svg/

查看更多
登录 后发表回答