d3.js用foreignObject替换circle

时间:2013-03-04 21:26:06

标签: javascript d3.js force-layout

我玩这个强制导向图布局的例子。 www.bl.ocks.org/GerHobbelt/3071239

或直接操纵,这里有小提琴, http://jsfiddle.net/BeSAb/

我想要的是替换圆形元素

  node = nodeg.selectAll("circle.node").data(net.nodes, nodeid);
  node.exit().remove();

  node.enter().append("circle")
      .attr("class", function(d) { return "node" + (d.size?"":" leaf"); })
      .attr("r", function(d) { return d.size ? d.size + dr : dr+1; })
      .attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; })
      .style("fill", function(d) { return fill(d.group); })
      .on("click", function(d) {
        console.log("node click", d, arguments, this, expand[d.group]);
        expand[d.group] = !expand[d.group];
    init();
      });

包含一个包含svg foreignObject

的group(g)元素
node = nodeg.selectAll("g.node").data(net.nodes, nodeid);
node.exit().remove();

var nodeEnter = node.enter().append("foreignObject")
//simplified for this demo
        .attr("class", function(d) { return "node" + (d.size?"":" leaf"); })
        .attr('width', '22px')
        .attr('height', '22px')
        .attr('x', -11)
        .attr('y', -11)
        .append('xhtml:div')
            .style("background",function(d){return fill(d.group)})
            .style("width","20px")
            .style("height","20px")
            .style("padding","2px")
       .on("click", function(d) {
       console.log("node click", d, arguments, this, expand[d.group]);
       expand[d.group] = !expand[d.group];
       init();
       });

图形构建正确但如果我尝试通过单击来扩展节点,则表示图形似乎未更新。这样就可以复制所有旧节点。

我制作另一个小提琴,您可以通过单击节点来显示此问题。 http://jsfiddle.net/xkV4b/

有谁知道我忘记了什么,或者问题是什么?

非常感谢!

1 个答案:

答案 0 :(得分:1)

您的输入附加内容应该与您在nodeg上的选择匹配。但即便如此,似乎d3在选择'foreignObject'时遇到了一些麻烦。这可能是提出d3 google group的问题/问题 - 这可能是一个错误。

但是你可以通过选择课程来解决这个问题。我将代码更新为:

node = nodeg.selectAll(".fo-node").data(net.nodes, nodeid);
node.exit().remove();

var nodeEnter = node.enter().append("foreignObject")
    .attr("class", function(d) { return "fo-node node" + (d.size?"":" leaf"); })
    .attr('width', '22px')
    ...

似乎work