如何让 css 个动画无论何时开始同时播放?

how to make css animations play simultaneously regardless of when it starts?

我有这样一种情况,我的多个 div 可以有一个带有 css 动画的 class,但在我的情况下,classes 代表一个状态。由于这些可以改变,使用 css 动画的状态可以在与另一个 div 不同的时间设置到 div 上。使用我现在为该状态设置的黄色闪烁效果,您会看到多个 div 在不同时刻闪烁,而不是同时闪烁。 所以问题是,有没有办法让 div 在同一时刻开始闪烁,就像你可以在 .000 毫秒开始动画一样?

我添加了一个片段来模拟我的问题:

function changeState(id) {
  let stateElement = document.getElementById(id);
  stateElement.classList.remove('green');
  stateElement.classList.add('yellow-blinking');
  stateElement.innerText = 'WARN';
}

setTimeout(() => changeState('state1'), 459);
setTimeout(() => changeState('state2'), 1321);
setTimeout(() => changeState('state3'), 2778);
    .state {
      margin: 8px;
      padding: 4px 0px 0px;
      border: 2px solid #000000;
      border-radius: 3px;
      font-family: Arial;
      font-size: 14px;
      font-weight: bold;
      height: 20px;
      width: 80px;
      text-align: center;
    }
    
   .yellow-blinking {
        background: #ffff00;
        color: #000000;
        animation: yellowflash-small 1s linear 0s infinite;
        -webkit-animation: yellowflash-small 1s linear 0s infinite;
    }
    @keyframes yellowflash-small {
        0% { background: #ffff00; }
        49% { background: #ffff00; }
        50% { background: #ffffff; }
        99% { background: #ffffff; }
    }

    @-webkit-keyframes yellowflash-small {
        0% { background: #ffff00; }
        49% { background: #ffff00; }
        50% { background: #ffffff; }
        99% { background: #ffffff; }
    }

    .green {
       background: #00d200;
       color: #000000;
    }
<div class="state green" id="state1">OK</div>
<div class="state green" id="state2">OK</div>
<div class="state green" id="state3">OK</div>

如您所见,闪烁之间并不同步。有没有办法让它们一起闪烁,而不管它什么时候达到那个状态?

最初将动画应用于元素并仅对 background-color 进行动画处理,然后使用 background-image 获得初始绿色。这样动画将在绿色后面开始 运行,我们只需移除绿色层即可显示它

function changeState(id) {
  let stateElement = document.getElementById(id);
  stateElement.classList.remove('green');
  stateElement.innerText = 'WARN';
}

setTimeout(() => changeState('state1'), 459);
setTimeout(() => changeState('state2'), 1321);
setTimeout(() => changeState('state3'), 2778);
.state {
  margin: 8px;
  padding: 4px 0px 0px;
  border: 2px solid #000000;
  border-radius: 3px;
  font-family: Arial;
  font-size: 14px;
  font-weight: bold;
  height: 20px;
  width: 80px;
  text-align: center;
  animation: yellowflash-small 1s linear infinite;
}

@keyframes yellowflash-small {
  0% {
    background-color: #ffff00;
  }
  49% {
    background-color: #ffff00;
  }
  50% {
    background-color: #ffffff;
  }
  99% {
    background-color: #ffffff;
  }
}

.green {
  background-image: linear-gradient(#00d200 0 0);
  color: #000000;
}
<div class="state green" id="state1">OK</div>
<div class="state green" id="state2">OK</div>
<div class="state green" id="state3">OK</div>