img src SVG changing the styles with CSS

后端 未结 22 1856
予麋鹿
予麋鹿 2020-11-22 01:16

html

\"Logo\"

css

.logo-img path {
           


        
22条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 01:47

    You will first have to inject the SVG into the HTML DOM.

    There is an open source library called SVGInject that does this for you. It uses the onload attribute to trigger the injection.

    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 themselves 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

提交回复
热议问题