我有一些相同类型的元素,我希望它们共享相同的 css 动画,但我希望它们在不同的时间开始/结束动画。
Codepen 为以下代码
html:
<div class="container">
<div class="box hidden"></div>
</div>
<div class="container">
<div class="box hidden"></div>
</div>
<div class="container">
<div class="box hidden"></div>
</div>
The css:
.container {
width: 100px;
height: 100px;
margin-bottom: 20px;
}
.box {
width: 100%;
height: 100%;
}
.box.hidden {
visibility: hidden;
}
.box {
animation: growIn 1s;
animation-timing-function: cubic-bezier(.46,.13,.99,.83);
transition: all .2s cubic-bezier(0.215, 0.61, 0.355, 1);
}
.container:first-child .box {
background-color: green;
}
.container:nth-child(2) .box {
background-color: orange;
}
.container:nth-child(3) .box {
background-color: red;
}
@keyframes growIn {
from {
transform: scale(0);
}
to {
transform: scale(1);
}
}
The box
元素一开始是隐藏的,然后使用 javascript 我在不同的时间从不同的框中删除这个类名:
const boxes = document.querySelectorAll(".box");
boxes.forEach(box => {
setTimeout(() => box.classList.remove("hidden"), Math.random() * 1000);
});
发生的情况是所有 3 个盒子同时结束动画。动画确实在不同的时间开始,但都一起结束。
这是为什么?
如果我做同样的事情,但添加一个类名而不是删除它(为了使动画开始),那么它的行为就像我想要的那样。
有任何想法吗?谢谢。