我需要将.screens
设置为display: none
,直到其动画开始。每个函数都有一个单独的animation-delay
所以我希望实现的是,一个函数将检查动画延迟的时间,然后确定setTimeout
函数的长度。
例: 如果.screens
的动画延迟为 3 秒,那么 3 秒后我希望显示从none
更改为block
.
到目前为止,我编写的函数代码如下:
var screens = document.getElementsByClassName('screen');
for (var i=0;i<screens.length;i++){
if (screens[i].style.animationDelay >=0){
setTimeout(function(){
this.style.display = "block";
}, this.style.animationDelay);
}
}
你可以试试这个。(您可以跳过第一部分,它只是为了生成带有随机animationDelay
screens
(
const generateScreens = () => {
for (let i = 0; i < 5; i++) {
let el = document.createElement('div');
el.className = 'screen';
el.style.animationDelay = Math.floor(Math.random() * 5) + 's';
document.body.appendChild(el);
}
}
generateScreens();
// code that you have asked for starts here
const screens = document.getElementsByClassName('screen');
[...screens].forEach(item => {
const delay = item.style.animationDelay.slice(0, item.style.animationDelay.length - 1);
setTimeout(() => {
item.style.display = 'block';
}, delay * 1000);
});
div.screen {
width: 40px;
height: 40px;
background: red;
border: 1px solid black;
display: none;
}
由于您无法animate
display
属性的状态/值从none
到block
,因此您可以使用visibility: hidden
/visibility: visible
对执行此操作,当然您也可以使用opacity: 0
/opacity: 1
执行此操作:
.screen {
visibility: hidden;
animation: animate forwards;
}
.screen:first-child {animation-delay: 1s}
.screen:nth-child(2) {animation-delay: 2s}
.screen:nth-child(3) {animation-delay: 3s}
@keyframes animate {
to {visibility: visible}
}
<div class="screen">1</div>
<div class="screen">2</div>
<div class="screen">3</div>
然后,您可以使用:nth-child
或:nth-of-type
选择器定位.screen
元素。