且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用CSS3动画更改文字?

更新时间:2023-10-28 12:53:46

您可以通过两种方式执行此操作.一种是使内容由伪元素管理.这意味着显示的内容将在CSS内应用;像这样:

There's two ways you could do this. One is to have the content managed by a pseudo element. This means that the displayed content would be applied inside CSS; like this:

h1:before{
    content: 'Original Text';
    font-size: 600%;
    animation-name: head;
    animation-duration: 4s;
    animation-iteration-count: infinite;
}

@keyframes head {
    0% {font-size:600%; opacity:1;}
    25% {font-size:570%; opacity:0;}
    50% {font-size:600%; opacity:1;}
    65% {font-size:570%; opacity:0;}
    80% {font-size:600%; opacity:1; content: "Changed Text"}
    90% {font-size:570%; opacity:0;}
    100% {font-size:600%;opacity:1; content: "Original Text"}
}

您可以执行此操作的另一种方法是在HTML中包含两个元素并在它们之间切换.您需要两个动画才能共同完成此操作,或者您可以仅偏移一个动画,如下所示:

The other way you could do this is by having two elements in the HTML and toggling between them. You'd need two animations to be working together to do this or you might be able to just offset one animation, like this:

<header>
    <h1 class="headtext" id="text1">Original Text</h1>
    <h1 class="headtext" id="text2">Changed Text</h1>
</header>

CSS

.headtext{
    font-size: 600%;
    animation-name: head;
    animation-duration: 4s;
    animation-iteration-count: infinite;
}

#text2{
    animation-delay: 2s;
}

@keyframes head {
    0% {font-size:600%; opacity:1;}
    50% {font-size:0; opacity:0;}
    100% {font-size:600%;opacity:1;}
}

我将font-size减小为0,以留出空间来容纳其他文本.这可能与您想要的效果有所不同.

I've reduced the font-size to 0 to give room for the other text to come in. This may be a different effect than you might want though.