在D3 Tree中鼠标悬停时添加文本

时间:2014-07-14 16:07:13

标签: javascript jquery d3.js

之前我已将文本添加到D3树中,但现在我在运行时创建节点,鼠标悬停上的文本不起作用。我知道正在调用该函数,因为我在mouseover上打印到控制台,按预期工作。我猜测移动节点和静态文本的转换会改变我添加其他文本的方式。代码如下:

jsfiddle.net/7L3A7/

我之前用于在鼠标悬停时添加文本的代码如下:

node.on("mouseover", function (d) {
                var g = d3.select(this); // The node
                // The class is used to remove the additional text later
                var info = g.insert('text')
                        .attr("x", function (d) {
                            return (d.parent.px);
                        })
                        .attr("y", function (d) {
                            return (d.parent.py);
                        })
                        .text(function (d) {
                            return "asdfadfg";
                        });

                console.log("adfhadfh");
            });

但是现在似乎无法在运行时添加节点。

1 个答案:

答案 0 :(得分:2)

我在这个小提琴中做了几处改变: http://jsfiddle.net/henbox/bGR8N/1/

首先,您要将<text>元素添加到<circle> SVG元素,以便您的HTML看起来像:

<circle class="node" r="4" cx="235" cy="480">
    <text x="235" y="240">Info on FOO</text>
</circle>

相反,您应该使用以下内容将文本和SVG形状添加到单独的g元素中:

var gelement = node.enter().append("g");
gelement.append("circle")...

所以你的HTML看起来像:

<g>
    <circle class="node" r="4" cx="268.57142857142856" cy="480"></circle>
    <text x="268.57142857142856" y="480">Info on FOO</text>
</g>

使用link.enter().insert("path", ".g.node")创建链接时,您还需要考虑新的结构,而不仅仅是link.enter().insert("path", ".node")

其次,此更改意味着鼠标悬停文本显示在父级级别,我认为这不是您想要的,所以我更改了{{1从x而非d.x访问,并为(d.parent.px)

执行相同操作

剩下的显而易见的问题是,鼠标输出时未删除y

相关问题