【问题标题】:Triggering a css animation as a transition in D3.js在 D3.js 中触发 css 动画作为过渡
【发布时间】:2018-05-24 08:13:48
【问题描述】:

我有一个使用 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");
}

【问题讨论】:

  • 我怀疑您在删除类和添加它们之间需要一些延迟,或者至少删除和添加类操作需要单独进行。尝试将后两个 -increment-decrement 操作包装在 setTimeout 中(尽管可能有一种更符合 d3 习惯的方式)。
  • 您也可以在过渡动画结束后使用延迟来删除 -increment-decrement 类。无论如何,如果添加和删除类的操作发生在同一个事件周期中,浏览器将不会知道该类实际上已更改,如果它恰好将类设置为与以前相同的值。

标签: javascript css animation d3.js transition


【解决方案1】:

您应该将添加新类的代码包装在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;
  }
}
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.12.0/d3.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 2020-06-05
    • 1970-01-01
    • 2014-04-19
    • 2014-06-05
    • 2012-07-07
    • 1970-01-01
    相关资源
    最近更新 更多