触发css动画作为D3.js中的过渡

时间:2017-12-10 18:43:02

标签: javascript css animation d3.js transition

我有一个帐户余额值,我使用d3显示。每一秒,值都会更新,并且根据是增加还是减少,我希望它分别闪烁绿色或红色。我有两个用于处理flash的css动画,每个动画都由一个可以添加到元素的修饰符类控制,如-increase-decrease

我正在使用d3的classed来控制这些类,但这就是我遇到一些问题的地方。每个更新循环,我检查并删除这两个类,然后有条件地添加适当的一个以触发新的动画。问题是,如果类保持与最后一个循环相同,则不会删除并再次添加它,因此当类更改时触发动画。我怎样才能每次触发其中一个动画?

function refreshBalance(accounts){
  let sum = 0;
  for(let i=0; i < accounts.length; i++){
    sum = sum + (accounts[i].value * accounts[i].rate);
  }

  let balance = d3.select(".balance").select(".currency-value");

  let diff;
  if ((sum - balance.attr("data-balance")) > 0){
    diff = "increment";
  } else {
    diff = "decrement";
  }

  balance.attr("data-balance", normalizeCurrency(sum, 4, 4))
    .text(normalizeCurrency(sum, 4, 4));

  balance.classed("-increment", false);
  balance.classed("-decrement", false);
  balance.classed("-increment", diff === "increment");
  balance.classed("-decrement", diff === "decrement");
}

1 个答案:

答案 0 :(得分:0)

您应该在setTimeout函数中包装添加新类的代码:

  balance.classed("-increment", false);
  balance.classed("-decrement", false);

  setTimeout(function() {
     balance.classed("-increment", diff === "increment");
     balance.classed("-decrement", diff === "decrement");
  });

小演示:

var divs = d3.select('body')
	.data([1,2,3,4,5,6])
  .enter()
  .append('div')
  .text(function(d,i) { return i; })
  
setInterval(function() {
  divs.classed("-increment", false);
  divs.classed("-decrement", false);

  setTimeout(function() {
    divs.classed("-increment", function(d, i) { return i % 2});
    divs.classed("-decrement", function(d, i) { return !(i % 2)});
  });
}, 3000);
div {
  font-size: 30px;
  font-weight: bold;
}

.-increment {
  animation:increment-animation 1.5s; 
}

.-decrement {
  animation:decrement-animation 1.5s; 
}

@keyframes increment-animation {
  0% {
    color: black;
  }
  20% {
    color: green;
  }
  40% {
    color: black;
  }
  60% {
    color: green;
  }
  80% {
    color: black;
  }
  100% {
    color: green;
  }
}

@keyframes decrement-animation {
  0% {
    color: black;
  }
  20% {
    color: red;
  }
  40% {
    color: black;
  }
  60% {
    color: red;
  }
  80% {
    color: black;
  }
  100% {
    color: red;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.12.0/d3.min.js"></script>