How to change color of SVG image using CSS (jQuery SVG image replacement)?

后端 未结 17 1969
死守一世寂寞
死守一世寂寞 2020-11-21 17:36

This is a self Q&A of a handy piece of code I came up with.

Currently, there isn\'t an easy way to embed an SVG image and then have access to the SVG elements vi

17条回答
  •  爱一瞬间的悲伤
    2020-11-21 18:16

    There is an open source library called SVGInject that uses the onload attribute to trigger the injection. You can find the GitHub project at https://github.com/iconfu/svg-inject

    Here is a minimal example using SVGInject:

    
      
        
      
      
        
      
    
    

    After the image is loaded the onload="SVGInject(this) will trigger the injection and the element will be replaced by the contents of the SVG file provided in the src attribute.

    It solves several issues with SVG injection:

    1. SVGs can be hidden until injection has finished. This is important if a style is already applied during load time, which would otherwise cause a brief "unstyled content flash".

    2. The elements inject themselved automatically. If you add SVGs dynamically, you don't have to worry about calling the injection function again.

    3. A random string is added to each ID in the SVG to avoid having the same ID multiple times in the document if an SVG is injected more than once.

    SVGInject is plain Javascript and works with all browsers that support SVG.

    Disclaimer: I am the co-author of SVGInject

提交回复
热议问题