同一CSS动画的不同动画持续时间

时间:2015-11-26 17:03:14

标签: javascript jquery html css animation

我正在尝试使用带有文本的多个div,它们都使用相同的CSS动画 - (闪烁),但它们都应以不同的速率闪烁。假设我希望第一个div每2秒闪烁一次,第二个div每4秒闪烁一次。

有没有办法做到这一点?

这是我的代码:

.blink {
  animation-duration: 2s;
  /*this is what i'm trying to change*/
  animation-name: blink;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  animation-timing-function: ease-in-out;
}
@keyframes blink {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 1;
  }
  51% {
    opacity: 0.1;
  }
  100% {
    opacity: 0.1
  }
}
<div class="blink">hello</div>
<div class="blink">explosion</div>

2 个答案:

答案 0 :(得分:2)

使用:first-child和:last-child,你可以控制每个孩子的动画持续时间

.blink:first-child {
animation-duration: 0.5s; /*this is what i'm trying to change*/
animation-name: blink;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: ease-in-out;
}
.blink:last-child {
animation-duration: 1s; /*this is what i'm trying to change*/
animation-name: blink;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: ease-in-out;
}

@keyframes blink {
    0% {
        opacity: 1;
    }
    50% {
        opacity: 1;
    }
    51% {
        opacity: 0.1;
    }
    100% {
        opacity: 0.1
    }
}

Demo

或相同的

.blink{
animation-name: blink;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: ease-in-out;
}
.blink:first-child {
animation-duration: 0.5s; /*this is what i'm trying to change*/
}
.blink:last-child {
animation-duration: 1s; /*this is what i'm trying to change*/
}

@keyframes blink {
    0% {
        opacity: 1;
    }
    50% {
        opacity: 1;
    }
    51% {
        opacity: 0.1;
    }
    100% {
        opacity: 0.1
    }
}

Demo

当你说(多个div)时你可以使用:nth-​​child(n)来表示像

这样的div
.blink:nth-child(1) {  // for first div
.blink:nth-child(2) {  // for second div
.... so on

答案 1 :(得分:0)

执行此操作的一种方法是将持续时间拆分为自己的类,并在HTML中使用多个类(以.blink { animation-name: blink; animation-iteration-count: infinite; animation-direction: alternate; animation-timing-function: ease-in-out; } .blink-1s { animation-duration: 1s; } .blink-2s { animation-duration: 2s; } .blink-3s { animation-duration: 3s; } @keyframes blink { 0% { opacity: 1; } 50% { opacity: 1; } 51% { opacity: 0.1; } 100% { opacity: 0.1 } }为主类):

<div class="blink blink-1s">one second</div>
<div class="blink blink-2s">two seconds</div>
<div class="blink blink-3s">three seconds</div>
 composer require google/apiclient:^2.0.0@RC