How to apply a style to an embedded SVG?

前端 未结 3 879
终归单人心
终归单人心 2020-11-22 12:13

When an SVG is directly included in a document using the tag, you can apply CSS styles to the SVG via the document\'s stylesheet. However, I am tryi

3条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 12:41

    Short answer: no, since styles don't apply across document boundaries.

    However, since you have an tag you can insert the stylesheet into the svg document using script.

    Something like this, and note that this code assumes that the has loaded fully:

    var svgDoc = yourObjectElement.contentDocument;
    var styleElement = svgDoc.createElementNS("http://www.w3.org/2000/svg", "style");
    styleElement.textContent = "svg { fill: #fff }"; // add whatever you need here
    svgDoc.getElementById("where-to-insert").appendChild(styleElement);
    

    It's also possible to insert a element to reference an external stylesheet:

    var svgDoc = yourObjectElement.contentDocument;
    var linkElm = svgDoc.createElementNS("http://www.w3.org/1999/xhtml", "link");
    linkElm.setAttribute("href", "my-style.css");
    linkElm.setAttribute("type", "text/css");
    linkElm.setAttribute("rel", "stylesheet");
    svgDoc.getElementById("where-to-insert").appendChild(linkElm);
    

    Yet another option is to use the first method, to insert a style element, and then add an @import rule, e.g styleElement.textContent = "@import url(my-style.css)".

    Of course you can directly link to the stylesheet from the svg file too, without doing any scripting. Either of the following should work:

    
    
    
      ... rest of document here ...
    
    

    or:

    
      
        
      
      ... rest of document here ...
    
    

    Update 2015: you can use jquery-svg plugin for apply js scripts and css styles to an embedded SVG.

    提交回复
    热议问题