Javascript 在每次迭代后更改动画持续时间
所以我有这些移动的动画框。它们从底部到顶部无限移动。 在他们到达顶端后,他们重新开始。 我可以通过一些sas和它们的random()函数改变它们的大小和速度。 但每次他们以相同的速度前进时,它看起来都很陈旧 因此,我尝试使用javascript在每次设置动画时改变每个框的持续时间。我这样做:Javascript 在每次迭代后更改动画持续时间,javascript,css,animation,sass,Javascript,Css,Animation,Sass,所以我有这些移动的动画框。它们从底部到顶部无限移动。 在他们到达顶端后,他们重新开始。 我可以通过一些sas和它们的random()函数改变它们的大小和速度。 但每次他们以相同的速度前进时,它看起来都很陈旧 因此,我尝试使用javascript在每次设置动画时改变每个框的持续时间。我这样做: let ignBox = document.querySelectorAll('.ign-box'); let $rand = 0; ignBox.forEach(box =>{ bo
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';
});
});
它起作用了。但每件物品都会发射很多次。似乎动画持续时间更改会立即再次触发事件!所以一个项目可能有8秒,然后跳到20秒,然后跳到5秒。随着JS的启用,他们现在正在跳跃,这是波涛汹涌的。
这是一个密码笔:
这是因为
animationiteration
在每次新迭代开始时都会触发,更改animationDuration
实际上会重新启动动画,因此它会进入半无限循环
一种方法是只运行css动画一次,然后在animationend
事件中,更改animationDurationand
并重新启动动画
css:
js:
关于如何重新启动css动画和黑客的文章
.animated{
animation: slowMoveUp 3s linear 1;
}
//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");
});
});