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

时间:2018-05-20 10:22:25

标签: javascript css timeout css-animations settimeout

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

2 个答案:

答案 0 :(得分:0)

由于animate 属性noneblock,您无法display 州/值,您可以使用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>

然后,您可以使用.screen:nth-child 选择器定位:nth-of-type 元素

答案 1 :(得分:0)

你可以试试这个。 (您可以跳过第一部分,只是随机生成screens animationDelay

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