我使用foreignObject包含了div的svg(我尝试使用rect而不是div,as in this example,但是可扩展性,最好的选择是div)。
我想在特定类的每个div的末尾添加一个svg圈。上面的例子为所有元素添加了圆圈,但现在我想用类选择器过滤它们。我怎样才能用d3实现这个目标?
var leafnodes = new Array();
d3.select("#input-container-div").selectAll(".leaf")
.each(function () {
leafnodes.push(d3.select(this).style("top"));
});
我使用上面的代码但导致“0px”,因为它的CSS没有为“top”定义值。
我也尝试了this question上的解决方案,但由于某种原因它不起作用。
答案 0 :(得分:2)
使用foreignObject
附加div时,将x和y值设置为foreignObject
,而不是div。因此,您需要获取选择外部对象的值,这些外部对象是div的父对象。
获得" x"每个div的父(foreignObject
)的值:
var leafnodes = new Array();
d3.select("#input-container-div").selectAll(".leaf")
.each(function () {
leafnodes.push(d3.select(this.parentNode).attr("x"));
});
例如,给出这个简单的SVG,我们可以在console.log中找到x和y位置:
var leafnodes = new Array();
d3.select("svg").selectAll("div")
.each(function () {
leafnodes.push({x: d3.select(this.parentNode).attr("x"),
y: d3.select(this.parentNode).attr("y")});
});
console.log(JSON.stringify(leafnodes))

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="300" style="border:1px red solid">
<foreignobject x="40" y="20" width="100" height="100">
<div style="border:1px green solid">I'm a div inside a SVG.</div>
</foreignobject>
<foreignobject x="300" y="120" width="100" height="100">
<div style="border:1px green solid">I'm another div inside a SVG.</div>
</foreignobject>
</svg>
&#13;