我想创建一个 javascript 函数,它可以接受一个通用的 D3 选择,并将它的重复项附加到一个 SVG 对象。
这是一个最低限度的工作示例:
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
svg = d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 300);
circle = svg.append("circle")
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 20)
function clone_selection(x, i) {
for (j = 0; j < i; j++) {
// Pseudo code:
// svg.append(an exact copy of x, with all the attributes)
}
}
clone_selection(circle, 5);
</script>
Mike Bostock 说这是不可能的here但那是很久以前的事了。
有没有人对如何实现这一目标有任何新想法?请记住,在函数内部
clone_selection
我们不知道 x 中的 svg 元素是/是什么。
最佳答案
这是另一种可能性:长期做事。这解决了使用 <use>
的问题不能设置 style
的元素或 transform
属性分开。
我很惊讶这个惊人的d3js
库本身没有这样的功能,但这是我的黑客:
function clone_d3_selection(selection, i) {
// Assume the selection contains only one object, or just work
// on the first object. 'i' is an index to add to the id of the
// newly cloned DOM element.
var attr = selection.node().attributes;
var length = attr.length;
var node_name = selection.property("nodeName");
var parent = d3.select(selection.node().parentNode);
var cloned = parent.append(node_name)
.attr("id", selection.attr("id") + i);
for (var j = 0; j < length; j++) { // Iterate on attributes and skip on "id"
if (attr[j].nodeName == "id") continue;
cloned.attr(attr[j].name,attr[j].value);
}
return cloned;
}
关于svg - D3 : Append duplicates of a selection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18517376/