CSS 动画方向:交替不工作

CSS animation-direction: alternate not working

谁能告诉我为什么 CSS 动画方向 属性 不起作用?

动画工作正常,但交替 属性 不工作...

.w3-animate-top{
  border : 6px solid red;
  animation-duration : 10s;
  margin-top : 300px;
}

.main{
    height : 100px;
    border : 6px solid white;
    text-align : center;
    background-color : yellow;
    animation-name : example;
    animation-duration: 2s;
    animation-direction: alternate;
}

@keyframes example {
  from {
    background-color: yellow;
  }
  to {
    background-color: white;}
  }
}
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
  
  <div class = 'main'>
    My Animation
    <p>hello rishi this is rajan</p>
  </div>

</body>
</html>

您需要为此动画分配至少 2 次交互才能使其完成交替动画:

animation-iteration-count: 2;

animation-iteration-count

作为补充,你可以赋值animation-fill-mode: both;让元素在动画前后都保持状态。

.w3-animate-top{
  border : 6px solid red;
  animation-duration : 10s;
  margin-top : 300px;
}

.main{
    height : 100px;
    border : 6px solid white;
    text-align : center;
    background-color : yellow;
    animation-name : example;
    animation-duration: 2s;
    animation-direction: alternate;
    animation-iteration-count: 2;
    animation-fill-mode: both;
}

@keyframes example {
  from {
    background-color: yellow;
  }
  to {
    background-color: white;
  }
}
<div class = 'main'>
  My Animation
  <p>hello rishi this is rajan</p>
</div>

或者你可以通过赋值

让它永远循环
animation-iteration-count: infinite;

您需要定义 animation-iteration-count 属性 的值类似于 number|infinite|initial|inherit
示例: animation-iteration-count: infinite;

来源:https://www.w3schools.com/cssref/css3_pr_animation-iteration-count.asp

.w3-animate-top{
  border : 6px solid red;
  animation-duration : 10s;
  margin-top : 300px;
}

.main{
    height : 100px;
    border : 6px solid white;
    text-align : center;
    background-color : yellow;
    animation-name : example;
    animation-duration: 2s;
    animation-direction: alternate;
    animation-iteration-count: infinite;
}

@keyframes example {
  from {
    background-color: yellow;
  }
  to {
    background-color: white;}
  }
}
<div class = 'main'>
    My Animation
    <p>Hello Rishi, This is Raeesh</p>
</div>