2014-11-24 142 views
0

爲了能夠平滑地在條形圖中過渡條形圖,我需要在調用transition()之前設置高度。如何獲取當前元素高度?

當圖表首先渲染條從圖表底部所需動畫了起來:

chart.svg.selectAll('.bar') 
     .attr('y', chart.options.height) 
     .attr('x', function (d) { 
      return chart.xScale(d.title); 
     }) 
     .attr('width', chart.xScale.rangeBand()) 
     .attr('height', function() { 
      return 0; 
     }) 
     .transition() 
     .attr('y', function (d) { 
      return chart.yScale(d.score); 
     }) 
     .attr('height', function (d) { 
      return chart.options.height - chart.yScale(d.score); 
     }); 

然而,當我改變數據我不想設定高度回0。相反,我需要將高度設置爲矩形的當前高度。我如何從attr函數訪問這個函數?

 .attr('height', function() { 
      return 0; // how do I get the current height 
     }) 

當我登錄this我可以訪問DOM元素,但不知道從哪裏裏去。我試過d3.select(this).attr('height'),但它總是返回null。

+1

如果高度已設置,則不需要重新設置。使用新數據,只需添加'.transition()。attr(「height」,...)'。 – 2014-11-24 18:51:18

回答

1

由於@LarsKotthoff是在他的評論暗示,只要掰開您最初的平局從您的更新:

// intial draw of bars 
node 
    .enter() 
    .append("rect") 
    .attr("class", "myBars") 
    .style("fill", "steelblue") 
    .attr('y', config.height) 
    .attr('x', function(d, i) { 
    return xScale(i); 
    }) 
    .attr('width', xScale.rangeBand()) 
    .attr('height', function() { 
    return 0; 
    });  

隨後擊發更新從當前位置移行條:

function update() { 
    node = svg 
    .selectAll(".myBars") 
    .data(data); 
    node 
    .transition() 
    .attr('y', function(d) { 
     return yScale(d); 
    }) 
    .attr("height", function(d) { 
     return config.height - yScale(d); 
    }); 
} 

這是我可以編碼的最簡單的example

enter image description here