简体   繁体   English

在D3选择中的每个对象上应用过渡

[英]apply a transition on each object in a D3 selection

I'm having troubles in understanding how to get each D3 object in a selection to apply a transition. 我在理解如何获取选择中的每个D3对象以应用过渡方面遇到麻烦。 Consider the follwoing code (here on jsfiddle ): 考虑以下代码(在jsfiddle上 ):

var svg = d3.select('svg');

var dataSet = [10, 20, 30, 40];

var circle = svg.selectAll('circle')
    .data(dataSet)
    .enter()
    .append('circle')
    .attr("r",function(d){ return d })
    .attr("cx", function(d, i){ return i * 100 + Math.random()*50 })
    .attr("cy",50)
    .attr("fill",'red')
   ;

circle.each(function(d,i) {
    this
  .transition()
  .duration(1000)
  .attr("cx",this.cx+100);
})

My use of this is wrong. this使用是错误的。 I've also tried with d3.select(this) but I get the dom object corresponding to D3 object. 我也尝试了d3.select(this)但是我得到了与D3对象相对应的dom对象。 I'm unable to get the D3 object to apply transition. 我无法获得D3对象来应用过渡。

The missing part is that you can supply a function to .attr('cx', function (d,i) { ... }) when using a transition, and inside that function you can access the cx attribute using this.getAttribute('cx') . 缺少的部分是,你可以提供一个功能.attr('cx', function (d,i) { ... })使用时的过渡,并在该函数内部可以访问cx使用属性this.getAttribute('cx')

Of course, you also want to make sure to turn it into a number using parseInt() , otherwise it will do string concatenation (because JS, sigh). 当然,您还需要确保使用parseInt()将其转换为数字,否则它将进行字符串连接(因为JS,叹气)。

So change your final line to: 因此,将您的最后一行更改为:

circle.transition().duration(1000).attr('cx', function(d, i) {
  return parseInt(this.getAttribute('cx')) + 100;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM