2013-02-19 53 views
8

我想在collapsible tree example的節點文本上添加超鏈接。添加超鏈接到可摺疊樹上的節點文本

我該怎麼做?

+0

已經有一個點擊處理函數對每個節點,你爲什麼不只是用它來執行你想用超鏈接執行的任何操作? – 2013-02-19 07:09:48

+0

好吧,點擊處理程序連接到示例中的圓圈,並且(afaik)無法將點擊處理程序添加到文本元素,所以這真是一個有效的問題。事實上,我無法弄清楚如何做到這一點。現在,我用一個'click'處理程序繪製第二個元素,重定向 – Marijn 2013-02-22 10:53:01

+0

並且圓上的點擊處理程序被附加到展開/摺疊,我們不想破壞它。 – Marijn 2013-02-22 11:03:22

回答

5

我是一個Javascript/SVG/d3js小白,但我通過放置一個超鏈接的透明矩形在文本上「解決」這個,這個解決方法是可以作爲bl.ock

nodeEnter 
    .append("a") 
    .attr("xlink:href", function (d) { return "http://www.example.com/flare/" + d.id; }) 
    .append("rect") 
     .attr("class", "clickable") 
     .attr("y", -6) 
     .attr("x", function (d) { return d.children || d._children ? -60 : 10; }) 
     .attr("width", 50) //2*4.5) 
     .attr("height", 12) 
     .style("fill", "lightsteelblue") 
     .style("fill-opacity", .3)  // set to 1e-6 to make transparent   
     ; 

我增加了一個額外的clickable styleadd .on("click", click) to the circle而不是組(g)元素。

這可行,但缺點是可點擊矩形的大小不與標籤的文本大小。

我真的很期待更好的解決方案,所以+1爲您的問題!

0

我加了文字的另一行到節點有關的鏈接的一些信息,比如:

nodeEnter.append("a") 
    .attr("xlink:href", function(d) { return d.path; }) 
    .append("text") 
    .attr("class", "clickable") 
    .attr("y", 16) 
    .attr("x", function (d) { return d.children || d._children ? -10 : 10; }) 
    .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; }) 
    .text(function(d) { return d.label; }) 

其中,路徑和標籤都希望爲每個節點的數據。

4

如果您刪除全局節點上單擊處理和連接2個不同的點擊處理程序:

  • 一爲圓
  • 一個文本

你可以有不同的行爲點擊文字時。如果您對該元素進行了一些樣式化,它可以看起來完全像超鏈接。

這裏看看我的小提琴: http://jsfiddle.net/empie/EX83X/

單擊處理

var nodeEnter = node.enter().append("g") 
      .attr("class", "node") 
      .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }); 

     nodeEnter.append("circle") 
      .attr("r", 1e-6) 
      .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }).on("click", click);; 

     nodeEnter.append("text") 
      .attr("x", function(d) { return d.children || d._children ? -10 : 10; }) 
      .attr("dy", ".35em") 
      .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; }) 
      .text(function(d) { return d.name; }) 
      .style("fill-opacity", 1e-6) 
     .attr("class", "hyper").on("click", clack); 

    function clack(d) { 
     alert(d.name); 
    } 

和CSS:

.hyper { 
    color: blue; 
    text-decoration: underline; 
} 

.hyper:hover { 
    color: yellow; 
    text-decoration: none; 
}