我正在尝试使用CSS
实现文本加载动画。我所拥有的是黑色文本,那么当页面加载时,文本将在几秒钟内开始用红色填充。
我面临的问题是,文本加载动画可以正常工作,但是当文本结束并以新行开头时,动画文本仍将继续在同一行上。
我该如何解决?
代码:
body {
background: #3498db;
font-family: sans-serif;
}
h1 {
position: relative;
color: rgba(0, 0, 0, .3);
font-size: 5em;
white-space: wrap;
}
h1:before {
content: attr(data-text);
position: absolute;
overflow: hidden;
max-width: 100%;
white-space: nowrap;
word-break: break-all;
color: #fff;
animation: loading 8s linear;
}
@keyframes loading {
0% {
max-width: 0;
}
}
<h1 data-text="Suspendisse mollis dolor vitae porta egestas. Nunc nec congue odio.">Suspendisse mollis dolor vitae porta egestas. Nunc nec congue odio.</h1>
答案 0 :(得分:32)
一个想法是考虑使用 inline 元素进行渐变着色。只需注意background-clip: text
中的browser support
body {
background: #3498db;
font-family: sans-serif;
}
h1 {
font-size: 5em;
}
h1 span {
background:
linear-gradient(#fff,#fff) left no-repeat,
rgba(0, 0, 0, .3);
background-size:0% 100%;
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
color: transparent;
animation:loading 5s forwards linear;
}
@keyframes loading {
100% {
background-size:100% 100%;
}
}
<h1><span>Suspendisse mollis dolor vitae porta egestas. Nunc nec congue odio.</span></h1>
为了更好地理解它的工作原理,这是一个基本示例,您可以在其中查看内联元素在背景色下的行为以及它与块级元素的区别:
.color {
font-size: 1.5em;
line-height: 1.5em;
border: 2px solid;
background: linear-gradient(red, red) left no-repeat;
background-size: 0% 100%;
animation: change 5s linear forwards;
}
@keyframes change {
100% {
background-size: 100% 100%
}
}
<span class="color">
lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume
</span>
<div class="color">
lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume
</div>
我只是使用background-clip:text
应用相同的逻辑来为文本而非背景着色:
.color {
font-size: 1.5em;
line-height: 1.5em;
border: 2px solid;
background: linear-gradient(red, red) left no-repeat;
background-size: 0% 100%;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
color: transparent;
animation: change 5s linear forwards;
}
@keyframes change {
100% {
background-size: 100% 100%
}
}
<span class="color">
lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume
</span>
<div class="color">
lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume
</div>