网页动画 API - 改变动画持续时间

Web Animations API - varying animation durations?

本文关键字:动画 持续时间 改变 API 网页      更新时间:2023-09-26

我正在试验目前仅适用于Webkit浏览器的Web Animations API。可以想象,文档有点稀疏:

  • 这是我在上面找到的一篇博客文章
  • 这是规格

我正在尝试做两件事:

  • 在动画结束前的随机时间点反转动画。
  • 错开动画中效果的持续时间。例如,对于 3 秒的动画,它的第一部分应该是 1.25 秒,第二部分应该是 1.75 秒。

下面是一个使用 Web 动画 API 的工作示例。我担心的是 3 个动画在 3 秒之间均匀分布。如何在不实例化多个 animationPlayer 对象的情况下以不同的方式将它们间隔开?

$('.box').click(function() {
  var animationPlayer = this.animate([{
    transform: 'translateX(0px)'
  }, {
    transform: 'translateX(600px)'
  }, {
    transform: 'translate(600px, 200px)'
  }], 3000);
  animationPlayer.onfinish = function(e) {
    console.log('complete!');
  }
  //  wiggle wiggle wiggle
  setTimeout(function() {
    animationPlayer.reverse();
    setTimeout(function() {
      animationPlayer.reverse();
    }, 250);
  }, 750);
});
.box {
  background-color: red;
  width: 200px;
  height: 200px;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'></div>

关于您的第一个问题,看起来Chrome实现仍然没有反向功能。这与你链接的文档一致。可能在金丝雀,但我还没有检查。

更正:阅读链接博客中的更新,看起来它已被添加到 Chrome。但是,它对我不起作用...

关于第二个问题,在第二个关键帧中指定偏移

如果第一个变换必须运行 1.25 秒,

总共 3 秒,这是 1.25/3 = .416,所以

$('.box').click(function() {
  var animationPlayer = this.animate([{
    transform: 'translateX(0px)'
  }, {
    transform: 'translateX(600px)', offset: 0.416
  }, {
    transform: 'translate(600px, 200px)'
  }], 3000);
  animationPlayer.onfinish = function(e) {
    console.log('complete!');
  }
  //  wiggle wiggle wiggle
  setTimeout(function() {
    animationPlayer.reverse();
    setTimeout(function() {
      animationPlayer.reverse();
    }, 250);
  }, 750);
});
.box {
  background-color: red;
  width: 200px;
  height: 200px;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'></div>