使用 CSS 动画和背景颜色显示文本

Text reveal using CSS animation and background color

我正在尝试制作文字显示 CSS 动画,如 this one。使用 ::before::after 似乎是一种过于复杂的方法,所以我尝试使用线性渐变背景颜色、背景位置或其他可能更简单的方法来做到这一点。

:root {
  --primary-rgba: rgba(17,184,106,1);
  --secondary-rgba: rgba(255,255,255,1);
}

@keyframes slidein {
  0% {
    background: transparent;
  }
  25% {
    background: linear-gradient(90deg, var(--secondary-rgba) 0%, var(--secondary-rgba) 50%, var(--primary-rgba) 50% var(--primary-rgba) 100%); 
  }
  50% {
    background: var(--secondary-hex);
  }
  75% {
    background: linear-gradient(90deg, var(--primary-rgba) 0%, var(--primary-rgba) 50%, var(--secondary-rgba) 50% var(--secondary-rgba) 100%); 
  }
  100%   {
    background: transparent;
  }
}

我什至想知道向动画中添加更多帧是否会使它按照我想要的方式工作并尝试 hacking in a bunch of (repetative) frames。仍然没有运气。

发现 CSS transitions likely don't support gradients yet 后,我尝试使用背景位置来显示文本但没有成功。

这两种方法都可行吗?

使用背景创建显示的唯一方法是考虑多个背景层,其中一个使用 background-clip:text,这样您还可以使用背景为文本着色并控制其位置。

这里是一个基于的例子。诀窍是让两层动画相同,然后最后我们为顶部动画制作动画,使其宽度为 0,同时将另一层(文本层)的宽度保持为 100%

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #8ce2ea;
  margin:0;
}

.reveal-text {
  position: relative;
  font-size: 50px;
  color: transparent;
  background-image: 
    linear-gradient(#f2f98b, #f2f98b), 
    linear-gradient(#fff,#fff);
  -webkit-background-clip:
    padding-box,
    text;
  background-clip:
    padding-box,
    text;
  background-size: 0% 100%;
  background-repeat: no-repeat;
  background-position: left;
  animation: revealer-text 0.8s 1s forwards;
}

@keyframes revealer-text {
  0% {
    background-size: 0% 100%;
  }
  50% {
    background-size: 100% 100%;
    background-position: left;
  }
  51% {
    background-size: 100% 100%;
    background-position: right;
  }
  100% {
    background-size: 0% 100%,100% 100%;
    background-position: right;
  }
}
<h1 class="reveal-text">
  I'm here.
</h1>

这可能不适用于所有浏览器,因此如果您想要更受支持的使用背景的方式,您将至少需要一个额外的元素,就像我在此处所做的那样