2016-02-23 92 views
2

我最近爲一個項目佔用了D3,而且我正面臨樹佈局的問題。當我最初加載樹佈局時,它在SVG中保持良好,如下面的屏幕截圖所示。 Initial state of tree when no nodes are opened節點擴展之後樹的位置

但是,一旦我開始打開節點,我打開的節點越多,開始向上越多,從而變得不可見,如下圖所示。

當我開始打開節點: When i start opening nodes 當所有的節點被打開: All of the nodes are opened.

正如你可以看到我所做的SVG滾動垂直,這樣我可以看到更大的樹木。

這裏是我創建樹佈局:

var tree = d3.layout.tree() 
     .nodeSize([55,30]); 

現在我找到了解決方案通過增加「G」元素的高度,它包含所有節點的每一次點擊,有一個節點上孩子,但這不是一個好的解決方案,因爲這會導致整個樹在每次發生這種情況時都會「跳躍」。

//creates the <g> element 
var gWidth = 90; 
var gHeight = 250; 
var vis = svg.append("g") 
      .attr('id', 'group') 
      .attr("transform", "translate(" + gWidth + "," + gHeight + ")"); 


function updateSvg(node){ 
//moves the g element 50px down on each click that has a child 
        if(node.children){ 
        gHeight +=50; 
        vis.attr("transform", "translate(" + gWidth + "," + gHeight + ")"); 
        } 
        else{ 
        gHeight-=50; 
        vis.attr("transform", "translate(" + gWidth + "," + gHeight + ")"); 
        // } 

} 

我也增加SVG的高度,如果有超過一定數量的節點,但我認爲這超出了我當前的問題的範圍。

有什麼我失蹤?

+0

只是檢查節點是否離開屏幕(< 0 || >高度)並相應地縮放svg – thatOneGuy

回答

1

我可以看到試圖解決這個問題有兩種方法:自動

1.滾動你的容器避免跳躍,與gHeight變量您的解決方案:

document.getElementById("container").scrollTop += 50; 

我真的不確定這一點,所以我認爲你會做得更好:

2.使用d3 zoom & pan方法縮放行爲工作得很好,看到

https://github.com/mbostock/d3/wiki/Zoom-Behavior

它歸結爲

var zoom = d3.behavior.zoom(); 
svg.call(zoom); 

,所以你可以擺脫滾動條和gHeight S的,基本上不用再擔心關於窗口邊界。