簡體   English   中英

D3.js對象中的超鏈接,第2部分

[英]Hyperlinks in D3.js objects, part 2

我是D3的新手,但根據以下示例將Reingold-Tilford樹放在一起: http : //bl.ocks.org/mbostock/4339184

我正在嘗試將超鏈接添加到每個鏈結之一的子節點上-基本上,任何在其前面帶有白色圓圈的節點。

我發現了有關如何添加超鏈接的有用說明-d3.js對象中的超鏈接 -但不幸的是,我只了解其中的一半。

作者寫道:

這很容易,只需添加更多“鍵”:“值”對。 例:

        "children": [
        {
            "name": "Google",
            "size": 3938,
            "url":  "https://www.google.com"

        },
        {
            "name": "Bing",
            "size": 3938,
            "url":  "http://www.bing.com"

        }
    ]

我同意,這很容易-我已經做到了。 但是,在完成之后,如何將頁面的代碼更改為,正如另一篇文章中的助手所寫的那樣,“在d3繪圖代碼中,為每個數據元素附加節點,然后包裝要成為的元素帶有svg:a標簽的可點擊鏈接:”

nodeEnter.append("svg:a")
.attr("xlink:href", function(d){return d.url;})  // <-- reading the new "url" property .append("svg:rect")
.attr("y", -barHeight / 2)
.attr("height", barHeight)
.attr("width", barWidth)
.style("fill", color)
.on("click", click);  // <- remove this if you like

這是我不明白的。 有人可以解釋一下如何修改此內容以使其與本示例中的文本保持一致嗎-http: //bl.ocks.org/mbostock/4339184

先感謝您。

馬特

首先,您需要檢查要追加的節點是否有子節點,因此可以區分哪些將是鏈接,哪些將是文本。 完成后,您可以追加正確的元素。 因此,與其像現在那樣僅添加文本元素,不如:

node.append("text")
    .attr("dx", function(d) { return d.children ? -8 : 8; })
    .attr("dy", 3)
    .attr("text-anchor", function(d) { return d.children ? "end" : "start"; })
    .text(function(d) { return d.name; });

遍歷他們,確定誰有孩子,並相應地添加正確的元素,如下所示:

node.each(function(d){
    var thisNode = d3.select(this);
    if (!d.children) {
        thisNode.append("a")
            .attr("xlink:href", function(d) { return d.url; })
            .append("text")
                .attr("dx", 8)
                .attr("dy", 3)
                .attr("text-anchor", "start")
                .text(function(d) { return d.name; });
    } else {
        thisNode.append("text")
            .attr("dx", -8)
            .attr("dy", 3)
            .attr("text-anchor", "end")
            .text(function(d) { return d.name; });      
    }
});

現在,只有沒有子節點的節點才會被超鏈接。 僅供參考:正如您所看到的,我遺漏了一些僅用於檢查子項的冗余功能,因為到那時您已經知道該節點是否有任何功能,您將不再需要這些功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM