我正在尝试做一个文本显示 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
这将允许您还使用背景为文本着色并控制其位置。
这是一个基于 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
关于html - 使用 CSS 动画和背景颜色显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57339684/