【问题标题】:Text reveal using CSS animation and background color使用 CSS 动画和背景颜色显示文本
【发布时间】:2019-08-03 15:27:34
【问题描述】:

我正在尝试制作一个文本显示 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之后,我尝试使用背景位置来显示文本,但没有成功。

这两种方法都可行吗?

【问题讨论】:

  • 请在您的问题中发布相关的minimal reproducible example 代码,包括适用的HTML;因为我的浏览器 - Chromium 和 Firefox - 由于引荐来源标头而无法与 Codepen 配合使用,显然,我不知道您在第一个链接中链接到的演示中发生了什么。
  • 背景被画在文字后面,所以即使你找到了一种动画背景的方法,你也不能像你想要的那样做。您将需要一个额外的元素
  • 这里是你可以用背景做的,但你至少需要一个伪元素:stackoverflow.com/a/53196294/8620333
  • @TemaniAfif 是的,你说得对,只是想多了,我不能做一个有背景的“揭示”。继续将您的 cmets 转换为答案,我会接受。

标签: html css css-animations linear-gradients


【解决方案1】:

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

这是一个基于a previous answer 的示例。诀窍是让两层动画相同,然后在最后动画顶部的一层使其宽度为 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>

这可能不适用于所有浏览器,因此如果您想要一种更受支持的使用背景的方式,您至少需要一个额外的元素,就像我在这里所做的 Clip-path alternatives for reveal text

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 2014-09-29
相关资源
最近更新 更多