1

我想扩展 d3 树布局以为每个最终节点提供超链接和文本

http://mbostock.github.io/d3/talk/20111018/tree.html

例如,如果你去

flare> analytics > ckuster > AgglomerativeClustr

我想在文本 AgglomerativeCluster 下我想有一个能够拥有自定义 HTML 的文本框。

我该怎么做?

4

2 回答 2

2

有几种方法可以实现您想要的,但我相信下面的解决方案既简单又高效。

我将从一个与您的示例类似的示例开始,并且也没有任何超链接:

链接到 jsfiddle - 起点

并将引导您完成所有必要但简单的修改。

首先,让我们为我们希望将标签作为超链接的节点添加字段“url”:

        {
            "children": [{
            "name": "AgglomerativeCluster",
            "size": 3938,
            "url": "http://www.example.com/"    
        }, {
            "name": "CommunityStructure",
            "size": 3812,
            "url": "http://www.example.com/"    

        }, {
            "name": "HierarchicalCluster",
            "size": 6714,
            "url": "http://www.example.com/"    

        }, {
            "name": "MergeEdge",
            "size": 743,
            "url": "http://www.example.com/"    
        }

现在,让我们编写代码来选择节点数据包含字段“url”中任何内容的所有标签,并为每个这样的标签添加适当的时钟处理程序,以打开对应的 url:(它还为鼠标悬停设置不同的光标指针,以便用户知道标签实际上是一个超链接)

d3.selectAll(".node text")
    .filter(function(d){ return d.url; })
    .style("cursor", "pointer")
    .on("click", function(d){
        document.location.href = d.url;
    });

而已!

链接到 jsfiddle - 完成示例

于 2014-05-06T12:44:57.077 回答
2

注意:当我完成这个时,我的好伙伴@VividD 已经提供了答案。但是因为 OP 表达了对自定义 HTML 的渴望,所以这可能仍然是相关的。

Basically one wants to mix HTML with SVG in one form or another, a common request. However, chances are you will not find a ready-made implementation of this since it takes time and has a fair amount of layout considerations to make it work (see the setting of x,y attributes in the fiddle I linked below - hardcoded for simplicity). Having said that, here is my attempt at helping you.

The most common solution is the use of an SVG:foreignObject. But be aware that IE does not support it. Here is a gist by the great Mike that showcases a very simple example. I took the liberty to extend it and create a FIDDLE with a slightly more elaborate example, a form with a textarea. I believe this should be enough to generate some ideas and get you going.

svg.append("foreignObject")
    .attr("x", 40)
    .attr("y", 40)
    .attr("width", 480)
    .attr("height", 240)
  .append("xhtml:body")
    ...

如果您没有完全解决您的问题,您可能需要考虑生成自己的小提琴(基于这个)。

于 2014-05-06T13:23:07.213 回答