仅使用 css 的多个文本块的文本淡入淡出

text fade in-out with multiple blocks of text using css only

我有 3 个文本块。我希望块 1 淡入并显示 3 秒,然后淡出。一旦它的不透明度达到 0,我希望文本块 2 淡入并显示 3 秒......与文本块 3 相同。我想我可以通过将 am 动画分配给所有 3 个和不同的 animation-delay 每个,但它们似乎最终都一致显示:

<main>
  <h2>Text block 1</h2>
  <h2>Text block 2</h2>
  <h2>Text block 3</h2>
</main>



@keyframes textFader {
  0% {
    opacity: 0;
  }
  25% {
    opacity: 1;
  }
  75% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

h2 {
    animation-name: textFader;
    animation-duration: 12s;   
    animation-timing-function: ease-in-out;        
    animation-iteration-count: infinite;
}

h2:first-of-type {
    animation-delay: 0s;
}
h2:nth-of-type(2) {
    animation-delay: 6s;
}
h2:last-of-type {
    animation-delay: 12s;
}

我知道这可以用 3 个独立的动画来完成:

   @keyframes textFader1 {
  0% {
    color: rgba(255, 255, 255, 0);
  }
  8% {
    color: rgba(255, 255, 255, 1);
  }
  25% {
    color: rgba(255, 255, 255, 1);
  }
  33% {
    color: rgba(255, 255, 255, 0);
  }
  100% {
    color: rgba(255, 255, 255, 0);
  }
}

@keyframes textFader2 {
  0% {
    color: rgba(255, 255, 255, 0);
  }
  34% {
    color: rgba(255, 255, 255, 0);
  }
  42% {
    color: rgba(255, 255, 255, 1);
  }
  59% {
    color: rgba(255, 255, 255, 1);
  }
  67% {
    color: rgba(255, 255, 255, 0);
  }
  100% {
    color: rgba(255, 255, 255, 0);
  }
}

@keyframes textFader3 {
    0% {
      color: rgba(255, 255, 255, 0);
    }
    66% {
      color: rgba(255, 255, 255, 0);
    }
    83% {
      color: rgba(255, 255, 255, 1);
    }
    91% {
      color: rgba(255, 255, 255, 1);
    }
    100% {
      color: rgba(255, 255, 255, 0);
    }
  }

但这对 1 人来说有点像 management/editing 噩梦,更不用说 3 人了(尤其是对于更复杂的关键帧)- 一定有更好的方法吗?

我知道这可以通过 JavaScript 轻松完成,但我需要一个仅 CSS 的解决方案。谁能看出我做错了什么?

h2 {
  opacity: 0;
  animation-name: textFader;
  animation-duration: 18s; /* <---{ 6sec * num(H2) = 18sec } */
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
}

h2:first-of-type { animation-delay: 0s; }
h2:nth-of-type(2) { animation-delay: 6s; }
h2:last-of-type { animation-delay: 12s; }

@keyframes textFader {
  0% {
    opacity: 0;
  } /* fade-in */
  11% {
    opacity: 1;
  } /* show */
  22% {
    opacity: 1;
  } /* fade-out */
  33% { /* <-------------------{ 100% / num(H2) = 33% } */
    opacity: 0;
  } /* waiting for the finish animation of other blocks */
  100% {
    opacity: 0;
  }
}
<main>
  <h2>Text block 1</h2>
  <h2>Text block 2</h2>
  <h2>Text block 3</h2>
</main>