此 CSS 使文本显示为打字机效果。然而,问题是因为 white-space: nowrap
在 CSS 中它只显示顶行。
所以如果我在单个 <p>
中有文本覆盖 4 行的元素,仅显示第一行。
p{
color: lime;
font-family: "Courier";
font-size: 20px;
margin: 10px 0 0 10px;
white-space: nowrap;
overflow: hidden;
width: 100%;
animation: type 4s steps(60, end);
}
@keyframes type{
from { width: 0; }
}
如果纯 CSS 不可能,是否有任何基于 JS 的解决方案?我不想尝试将一个段落分成几个 <p>
特别是当宽度改变时,换行点会变得困惑。
最佳答案
So if I have text in a single <p> element that covers 4 lines, only the top line gets shown.
根据上述陈述,我假设问题是关于跨越多行的文本,即使为元素提供了最大可能的宽度(也就是说,仅更改 width
不是一个选项).
正如我在评论中提到的那样,如果您删除 white-space: nowrap
,像这样的动画的问题是,它不会像打字机效果一样工作,因为全文会同时开始输入(因为只有 width
正在动画),这将导致奇怪的动画,因为当 width
较小时,文本将环绕当它增加时,文本也会移动到前面的行。
文本需要被限制在一行中,或者它应该被分成多个 p
标签,就像下面的代码片段一样。如果这些都无法完成,那么您应该考虑使用 JavaScript(或任何库)。
body {
background: #000;
padding-top: 10px;
width: 500px;
border: solid white 1px;
}
p {
color: lime;
font-family: "Courier";
font-size: 20px;
margin: 10px 0 0 10px;
white-space: nowrap;
overflow: hidden;
width: 0;
animation: type 4s steps(60, end) forwards;
}
p:nth-child(2) {
animation-delay: 4s;
}
p:nth-child(3) {
animation-delay: 8s;
}
p a {
color: lime;
text-decoration: none;
}
span {
animation: blink 1s infinite;
}
@keyframes type {
to {
width: 100%;
}
}
@keyframes blink {
to {
opacity: .0;
}
}
::selection {
background: black;
}
<p>hi folks, this is typing animation using</p>
<p>CSS. But on the second line it never</p>
<p>shows up. The other lines get cut off.</p>
下面是如果你只是删除 white-space: nowrap
会发生什么。您可以看到它不再像打字机那样工作。
body{
background: #000;
padding-top: 10px;
width: 500px;
border: solid white 1px;
}
p{
color: lime;
font-family: "Courier";
font-size: 20px;
margin: 10px 0 0 10px;
overflow: hidden;
width: 100%;
animation: type 4s steps(60, end);
}
p:nth-child(2){
animation: type2 8s steps(60, end);
}
p a{
color: lime;
text-decoration: none;
}
span{
animation: blink 1s infinite;
}
@keyframes type{
from { width: 0; }
}
@keyframes type2{
0%{width: 0;}
50%{width: 0;}
100%{ width: 100; }
}
@keyframes blink{
to{opacity: .0;}
}
::selection{
background: black;
}
<p>hi folks, this is typing animation using CSS But on the second line it never shows up. The other lines get cut off.</p>
如果您愿意使用完全基于 JS 的方法来实现此动画,那么您可以遵循 this Fiddle 中使用的方法。 .是the Fiddle的定制版贡献者Akshay .它使用一个循环(基于setInterval
),然后在每次迭代中修改元素的内容。首先它只获取内容的第一个字符,然后是前两个、前三个等等,直到内容被完全打印出来。循环和间隔让它看起来就像是在打字。
您可以通过在函数调用中传递所需的值来控制键入速度,以及在键入行之间添加的延迟。
关于javascript - 动画 chop <p> 中的多行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37108305/