【问题标题】:text fade in-out with multiple blocks of text using css only仅使用 css 的多个文本块的文本淡入淡出
【发布时间】:2020-10-07 15:30:26
【问题描述】:

我有 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 来说是管理/编辑的噩梦,更不用说 3(尤其是对于更复杂的关键帧)——一定有更好的方法吗?

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

【问题讨论】:

    标签: css-animations delay fade keyframe


    【解决方案1】:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-21
      • 2016-04-02
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 2015-08-08
      相关资源
      最近更新 更多