Change attributes defined in defs on use element

前端 未结 3 568
旧时难觅i
旧时难觅i 2021-02-02 09:56

How can I achieve changing the style of an \"use element\", defined in defs, through scripting? I was trying to move in the w3c working draft interfaces, but I lost in that laby

3条回答
  •  伪装坚强ぢ
    2021-02-02 10:39

    As you can see in my test page, if you define the visual style of an element inside the section of a document you cannot override that style on the instance, not through a visual attribute, style attribute, or CSS class applied to the .

    Snapshot of test results from linked SVG file, showing that only unstyled elements can be overridden

    Further, you cannot use a visual attribute on the element to cascade styles down to elements of the source; you must use CSS styling for this.

    You'll have to:

    1. Ensure that your defined elements have no visual style applied, and
    2. Use either CSS or set a manually-parsed-or-created style attribute, e.g.

      node.setAttribute('style','fill:blue');
      

    As noted here you can use either setAttribute(...) or setAttributeNS(null,...) for SVG attributes.

    Update: To answer your second question:

    What if the referenced element is a "g" which contains 2 other elements, like a rect and a text?

    You cannot use CSS rules to select the pseudo-children of a ; they simply don't exist. What you can do, however, is apply the unchanging styling that you want to preserve inside the and then apply the style you want on the .

    For example:

    
      
        
        
        
        JC!
      
    
    
    
    

    This only works if you want all changeable items to have their attributes set the same way.

    Unlike HTML, the markup in SVG is the presentation. What I've suggested above is a bit of a hack that happens to work, but in general elements are designed to instantiate the full appearance of a definition. If you need custom appearance per instance, perhaps you should consider cloning elements, modifying properties, and adding those to the document instead of hacking a .

提交回复
热议问题