【问题标题】:changing the animation duration after each iteration每次迭代后更改动画持续时间
【发布时间】:2019-01-04 19:41:08
【问题描述】:

所以我有这些移动的动画框。它们从底部无限移动到顶部。 在他们到达顶部之后,他们重新开始。 我最初可以通过一些 sass 和它们的 random() 函数来改变它们的大小和速度。 但是每次都以相同的速度前进,所以看起来很陈旧。

所以我尝试使用 javascript 来改变每个框每次动画的持续时间。我这样做了:

let ignBox = document.querySelectorAll('.ign-box');
  let $rand = 0;
  ignBox.forEach(box =>{
    box.addEventListener('animationiteration', function(){

       $rand = (Math.floor(Math.random() * 20) + 3);
      console.log(this);
        this.style.animationDuration =  $rand + 's';
    });
  });

它有效。但它为每个项目触发了很多次。似乎动画持续时间更改立即再次触发事件!所以一个项目可能有 8s 然后它跳到 20s 然后到 5s。启用 JS 后,他们现在跳得断断续续。 这是一个代码笔: https://codepen.io/saltnpixels/pen/yqzZBb

【问题讨论】:

    标签: javascript css animation sass


    【解决方案1】:

    这是因为animationiteration 在每次新迭代开始时触发,而更改animationDuration 实际上会重新启动动画,所以它进入了一个半无限循环。

    一种方法是只运行 css 动画 1 次,然后在 animationend 事件上,更改 animationDurationand 并重新启动动画。

    css:

    .animated{
      animation: slowMoveUp 3s linear 1;
    }
    

    js:

    //change box animation times to vary things up
      let ignBox = document.querySelectorAll('.ign-box');
      let $rand = 0;
      ignBox.forEach(box =>{
        box.classList.add("animated");
        box.addEventListener('animationend', function(){
          this.classList.remove("animated");
          $rand = (Math.floor(Math.random() * 20) + 3);
          console.log(this);
          this.style.animationDuration =  $rand + 's';
          void this.offsetWidth; // hack to reflow css animation
          this.classList.add("animated");
        });
      });
    

    感谢this link 了解如何重新启动 CSS 动画以及 hack。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      相关资源
      最近更新 更多