繁体   English   中英

使用DOM的createElement创建空元素

[英]Create empty element with DOM's createElement

问题是我想使用JavaScript动态创建svg文件。 但是,当绘制路径时,它不会渲染到屏幕上(过去2到3个小时我一直在寻找问题)...这就是...当使用document.createElement创建元素时,我们得到<element> </element> 但是path元素必须创建为空元素- <path .../> 所以。 如何使用document.createElement创建空元素? 或者,也许我无法使用document.createElement做到这一点,而不得不使用JQuery来做到这一点?

let b1b2 = document.createElement('path');
b1b2.setAttribute('d', 'M0 0 L100 100');
b1b2.setAttribute('fill', 'none');
b1b2.setAttribute('stroke', 'red');
b1b2.setAttribute('stroke-width', '5');

<path d="M0 0 L100 100" fill="none" stroke="red" stroke-width="5"></path>

SVG有一个特殊的名称空间要求。 您需要使用document.createElementNS

document.createElementNS('http://www.w3.org/2000/svg', 'path');

例:

 let b1b2 = document.createElementNS('http://www.w3.org/2000/svg', 'path'); b1b2.setAttribute('d', 'M0 0 L100 100'); b1b2.setAttribute('fill', 'none'); b1b2.setAttribute('stroke', 'red'); b1b2.setAttribute('stroke-width', '5'); document.getElementById('svg').appendChild(b1b2); 
 <svg id="svg"></svg> 

暂无
暂无

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

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