根据动画延迟设置超时功能



我需要将.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);
}
}

你可以试试这个。(您可以跳过第一部分,它只是为了生成带有随机animationDelayscreens(

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;
}

由于您无法animatedisplay属性的状态/值noneblock,因此您可以使用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元素

最新更新