2014-10-17 52 views
2

問題簡述:如何訪問this.selection.exit()的副產品中的整個this.selectiond3.js使用exit()和enter()轉換

我試圖做一個d3.js轉換序列。我知道如何使用transition.transition()函數來創建序列,但這是我的問題。

序列應該是:[刪除.exit()節點]→[移動節點]→[添加.enter()節點]

代碼是:

 this.selection.exit().remove(); 
     this.selection 
      .style("left", this.styleLeft) 
      .style("top", this.styleTop) 
      .style("width", this.styleWidth) 
      .style("height", this.styleHeight); 
     this.selection.enter().append("div") 
      .attr("class", "node") 
      .style("left", this.styleLeft) 
      .style("top", this.styleTop) 
      .style("width", this.styleWidth) 
      .style("height", this.styleHeight); 

如果我添加transition()到每個上述的命令,所有轉換將在同一時間開始。 .delay()似乎無法在一次多個轉換中正常工作。

所以我想使用與.transition()分局,但如果我將第二個命令應用到第一個,我只有.exit()選擇。

編輯1:

示例如何不起作用:

 this.selection.exit().transition() 
     .duration(1000).style("opacity", 0).remove(); 

     this.selection.transition().delay(1010) 
      .duration(1000) 
      .style("left", this.styleLeft) 
      .style("top", this.styleTop) 
      .style("width", this.styleWidth) 
      .style("height", this.styleHeight) 

     this.selection.enter().append("div") 
      .attr("class", "node") 
      .style("opacity", 0) 
      .style("left", this.styleLeft) 
      .style("top", this.styleTop) 
      .style("width", this.styleWidth) 
      .style("height", this.styleHeight) 
      .transition() 
      .delay(2020) 
      .duration(1000) 
      .style("opacity", 1); 

錯誤的位置:最後的過渡沒有啓動,因此所有的新節點是不透明的。但是,如果我禁用第二個轉換,它會起作用。

編輯2:

http://jsfiddle.net/dq6d117g/6/

如果函數得到的轉換過程中再次被調用時出現問題。

另外,延遲應該只要動畫。如果沒有動畫,延遲應該是0.這就是爲什麼我想要使用結束事件。

+0

使用'.delay()'應該工作在這裏 - 你可以給它沒有一個例子嗎? – 2014-10-17 09:11:47

+0

請參閱編輯1 – Powerswitch 2014-10-17 10:05:01

+0

謝謝,但請您將此作爲一個可重複的示例嗎?我想運行它看看會發生什麼。 – 2014-10-17 10:42:41

回答

3

您可以使用d3.transition().each()到鏈的轉變上預存選擇按邁克·博斯托克的answer here,但是,在我的測試中,它沒有跳過不必要的轉換,所以我加了條件語句跳過空選擇過渡:

http://jsfiddle.net/dq6d117g/8/

var transition=d3.transition().duration(2000); 

if (!selection.exit().empty()) transition=transition.each(function(){ 
    selection.exit() 
     .transition() 
     .style("opacity", 0) 
     .remove(); 
}).transition(); 

if (!selection.empty()) transition=transition.each(function(){ 
    selection.transition() 
    .style("height", function (d) { 
     return (d.value * 10) + "px"; 
    }); 
}).transition(); 

transition.each(function(){ 
    selection.enter() 
     .append("div") 
     .attr("class", "bar") 
     .attr("id", function (d) { 
      return d; 
     }) 
     .style("opacity", 0) 
     .style("height", function (d) { 
      return (d.value * 9) + "px"; 
     }) 
     .text(function (d) { 
      return d.id 
     }) 
     .transition() 
     .style("opacity", 1) 
     .style("height", function (d) { 
      return (d * 10) + "px"; 
     }); 
});