Change text with a CSS3 animation?

前端 未结 2 725
眼角桃花
眼角桃花 2020-12-28 09:43

In my website I want to have a header that fades in and out, then in with different text, then out, then back to normal (looped). Here\'s how I would like it to work:

<
2条回答
  •  情话喂你
    2020-12-28 10:16

    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:

    CSS

    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"}
    }
    

    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:

    HTML

    Original Text

    Changed Text

    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;}
    }
    

    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.

提交回复
热议问题