简体   繁体   English

带有USE标记的SVG无法呈现

[英]SVG with USE tag not rendering

The DOM already includes an empty SVG tag ( svg ). DOM已经包含一个空的SVG标记( svg )。 When I try to dynamically append a USE tag of an existing SVG symbol ( symbol ) with an id ( iconId ): 当我尝试动态附加具有id( iconId )的现有SVG符号( symbol )的USE标记时:

svg.empty();
svg[0].setAttribute('viewBox', symbol.getAttribute('viewBox'));
svg.append('<use xlink:href="#' + iconId + '"></use>');

it no longer renders the SVG. 它不再呈现SVG。 In Chrome, it renders if I add: 在Chrome中,如果我添加,则呈现:

 element.html(element.html());

or manually manipulate the viewBox attribute, but that's not a real solution and IE doesn't like it at all. 或手动操作viewBox属性,但这不是一个真正的解决方案,IE根本不喜欢它。 It's worth mentioning that if I append SVG graphics directly, the element renders. 值得一提的是,如果我直接附加SVG图形,则元素呈现。

What is happening here and why isn't the SVG drawing after appending the USE tag? 这里发生了什么,为什么在附加USE标签后没有SVG绘图?

After all it was indeed a matter of namespaces. 毕竟它确实是命名空间的问题。

Specifically, SVG elements and attributes must be created and set using document.createElementNS and node.setAttributeNS . 具体而言,必须使用document.createElementNSnode.setAttributeNS创建和设置SVG元素和属性。

 $(document).ready(function(evt) { var svgns = 'http://www.w3.org/2000/svg', xlinkns = 'http://www.w3.org/1999/xlink', use = document.createElementNS(svgns, 'use'); use.setAttributeNS(xlinkns, 'xlink:href', '#save'); document.getElementById('useSVG').appendChild(use); }); 
 #svgStore { display: none; } #useSVG { width: 16px; height: 16px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <svg style="display:none;" id="svgStore" style="display: none;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <symbol viewBox="0 0 16 16" id="save"><title>save</title> <g id="svgstore3748a955346b4a088bbdc55a22f56504_x31_6_13_"> <path style="fill-rule:evenodd;clip-rule:evenodd;" d="M9,4h2V2H9V4z M13,13H3v1h10V13z M13,11H3v1h10V11z M13,0H0v16h16V3L13,0z M3,1h9v4H3V1z M14,15H2V8h12V15z M13,9H3v1h10V9z"> </path> </g> </symbol> </svg> SVG use: <svg id="useSVG" xmlns="http://www.w3.org/2000/svg"></svg> 

Thanks to @RobertLongson and http://www.kevlindev.com/tutorials/basics/shapes/js_dom/ for directing to the answer. 感谢@RobertLongson和http://www.kevlindev.com/tutorials/basics/shapes/js_dom/指导答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM