javascript 动态呈现的 SVG 未显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17520337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically rendered SVG is not displaying
提问by Royal Pinto
I have the following svg object which if I put in html page directly without using code(static) it renders properly.
我有以下 svg 对象,如果我直接放入 html 页面而不使用代码(静态),它会正确呈现。
but same svg content if I insert into my html page using JavaScript it is not showing and if I open it in firebug and inspect svg and try to edit svg tag, it displays.
但是相同的 svg 内容,如果我使用 JavaScript 插入到我的 html 页面中,它不会显示,如果我在 firebug 中打开它并检查 svg 并尝试编辑 svg 标签,它会显示。
What could be the problem
可能是什么问题呢
<svg height="100" width="100">
<rect width="100" height="100" style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)"></rect>
</svg>
I am adding svg dynamically using below code, here container will be my div which is there under body
我正在使用下面的代码动态添加 svg,这里的容器将是我的 div,它在 body 下
viewPort = document.createElementNS('http://www.w3.org/2000/svg','svg');
viewPort.setAttribute('height', 100);
viewPort.setAttribute('width', 100);
container.innerHTML = '';
container.appendChild(viewPort);
After this I am adding rect inside this using
在此之后,我在里面添加了 rect 使用
boardElement = document.createElement('rect');
boardElement.setAttribute('width', '100');
boardElement.setAttribute('height', '100');
boardElement.setAttribute('y', '1');
boardElement.setAttribute('x', '1');
boardElement.setAttribute('style', "fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)");
viewPort.appendChild(boardElement);
回答by Lkrups
The element boardElement
should be declared like so
元素boardElement
应该像这样声明
boardElement = document.createElementNS("http://www.w3.org/2000/svg", "rect");
boardElement = document.createElementNS("http://www.w3.org/2000/svg", "rect");