如何克隆dom的一个元素或块? [英] How do I clone an element or chunk of dom?
问题描述
我一直在尝试用D3创建一个漂亮的树。
I have been trying to create a beautiful tree with D3.
对于节点我有一个SVG模板在一个隐藏的div。但我一直在尝试D3的许多功能克隆模板,但都没有运行。
And for the nodes I have a SVG "template" in a hidden div. But I have been trying with many functions of D3 to "clone" the "template" but all didn't run.
最后的javascript代码是:
The last javascript code is:
...
var node = svg.selectAll("g.node")
.data(nodes)
.enter()
.append("svg:g")
.attr("transform",
function(d)
{
return "translate(" + d.y + "," + d.x + ")";
}
);
var template_box = d3.select("#layer1");
console.log(template_box);
node.insert(template_box);
...
html的卡牌是:
...
<body>
<svg width="400" height="400">
<g
id="layer1"
transform="translate(-208.375,-410.5)">
<rect
...
b $ b
推荐答案
如果你想在前面定义一些形状,然后在图中的不同位置重复使用,你将有更好的结果与svg < defs>
和< use>
。有关背景,请参见这个简单示例。你可以这样创建你的形状:
If you are trying to define some shapes up front and then reuse them at different positions in the diagram, you are going to have better results with svg's <defs>
and <use>
. See this simple example for background. You can create your shape up front like this:
<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="400">
<defs>
<g id="layer1" transform="translate(-208.375,-410.5)">
<rect
...
< g>
的内容,您只需回到其定义。所以你的代码将是这样:
Then instead of trying to clone the content of the <g>
, you simply refer back to it's definition. So your code would be something like this:
var node = svg.selectAll("g.node")
.data(nodes)
.enter()
.append("g")
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; } )
node.append("use")
.attr("xlink:href","#layer1")
请注意,svg定义中的xlink命名空间很重要。
Note that the xlink namespace in the svg definition is important.
UPDATE:这是上述方法的完整工作示例:
UPDATE: Here is a full working example of the above approach:
http://bl.ocks.org/explunit/5988971
这篇关于如何克隆dom的一个元素或块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!