2014-11-24 145 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