Html 使用 DOM 将 SVG 元素添加到现有 SVG
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16488884/
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
Add SVG element to existing SVG using DOM
提问by biggdman
I have a HTML construction that resembles the following code:
我有一个类似于以下代码的 HTML 结构:
<div id='intro'>
<svg>
//draw some svg elements
<svg>
</div>
I want to be able to add some elements to the SVG defined above using javascript and DOM. How would I accomplish that? I was thinking of
我希望能够使用 javascript 和 DOM 向上面定义的 SVG 添加一些元素。我将如何做到这一点?我在想
var svg1=document.getElementById('intro').getElementsByTagName('svg');
svg1[0].appendChild(element);//element like <line>, <circle>
I am not very familiar with using DOM, or how to create the element to be passed to appendChild so please help me out with this or perhaps show me what other alternatives I have to solve this issue. Thanks a lot.
我对使用 DOM 或如何创建要传递给 appendChild 的元素不是很熟悉,所以请帮我解决这个问题,或者告诉我我必须解决这个问题的其他替代方法。非常感谢。
回答by m93a
If you want to create an HTML element, use document.createElement
function. SVG uses namespace, that's why you have to use document.createElementNS
function.
如果要创建 HTML 元素,请使用document.createElement
函数。SVG 使用命名空间,这就是你必须使用document.createElementNS
函数的原因。
var svg = document.getElementsByTagName('svg')[0]; //Get svg element
var newElement = document.createElementNS("http://www.w3.org/2000/svg", 'path'); //Create a path in SVG's namespace
newElement.setAttribute("d","M 0 0 L 10 10"); //Set path's data
newElement.style.stroke = "#000"; //Set stroke colour
newElement.style.strokeWidth = "5px"; //Set stroke width
svg.appendChild(newElement);
This code will produce something like this:
此代码将产生如下内容:
<svg>
<path d="M 0 0 L 10 10" style="stroke: #000; stroke-width: 5px;" />
</svg>
createElement
:
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
createElement
:
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
createElementNS
:
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS
createElementNS
:
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS
回答by ragingsquirrel3
If you're dealing with svg's a lot using JS, I recommend using d3.js. Include it on your page, and do something like this:
如果您经常使用 JS 处理 svg,我建议您使用 d3.js。将它包含在您的页面上,然后执行以下操作:
d3.select("#svg1").append("circle");