CSS動畫Animation

動畫

以前說的過渡也是屬於動畫的範圍,只不過它只能是開始到過渡這兩個點,中間由瀏覽器去完成,而動畫容許開發者一幀一幀的去編碼。css

@keyframes

要執行的動畫都寫在這個規則裏html

my-css是自定義的名字瀏覽器

@keyframes my-css{
    from {top:0px;}
    to {top:200px;}
}

from就是以前的狀態,to是以後的狀態,嗯,這個其實和過渡沒啥區別,這是第一種寫法。動畫

而後就是這行代碼編碼

animation: my-css 5s;

完整代碼code

<!doctype html>
<html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <style type="text/css">
            .container{
                text-align: center;
                line-height: 200px;
                width: 200px;
                height: 200px;
                background: skyblue;

                /*關鍵代碼*/
                animation: my-css 5s;
                
            }
            @keyframes my-css{
                from {width:200px;}
                to {width:400px;}
            }
            
        </style>
    </head>
    <body>
        <div class="container">狠人大帝</div>
    </body>
</html>

這只是單純一種屬性的變化,多種屬性的變化是這樣的orm

@keyframes my-css{
    from {
        width:200px;
        height: 200px;
        background: skyblue;
    }
    to {width:400px;
        height: 400px;
        background: pink;
    }
}

接下來是一幀一幀的完成htm

@keyframes my-css{
    0%   {
        top:0px;left: 0px;
        transform: rotate(0deg);
        background: skyblue;
    }
    25%  {
        left:200px; 
        top:0px;
        transform: rotate(45deg);
        background: pink;
    }
    50%  {
        top:200px; 
        left:200px;
        transform: rotate(90deg);
        background: brown;
    }
    75%  {top: 200px; 
        left:0px;
        transform: rotate(135deg);
        background: #456920;
    }
    100% {top:0px; 
        left:0px;
        transform: rotate(180deg);
        background: skyblue;
    }
}

如此動畫的編寫規則就是這樣,接下來看animation屬性utf-8

animation

它是多個屬性的集合開發

animation: name duration timing-function delay iteration-count direction fill-mode play-state;
  • name 指定要綁定到選擇器的關鍵幀的名稱
  • duration 動畫執行的時間
  • timing-function 速度曲線
  • delay 動畫延遲的時間
  • iteration-coun 動畫執行的次數
    • n 指定播放的次數
    • infinite 無限循環
  • direction 是否應該輪流反向播放動畫
    • reverse 方向播放
    • normal 默認,正常播放
    • alternate 奇數次正向播放,偶數次反向播放
    • alternate-reverse 奇數次反向播放,偶數次正向播放
  • fill-mode 規定當動畫不播放時(當動畫完成時,或當動畫有一個延遲未開始播放時),要應用到元素的樣式
    • none 動畫開始和結束都不會用規則定義中的樣式
    • forwards 動畫結束後保留最終的樣式
    • backwards 動畫開始前,若有延遲,使用第一幀的屬性值
    • both 前面兩個的融合版
  • play-state 指定動畫是否正在運行或已暫停。
    • paused 指定暫停動畫
    • running 指定正在運行的動畫

以上屬性若是單獨使用應該加上前綴animation-

改變CSS代碼

.container{
    text-align: center;
    line-height: 200px;
    width: 200px;
    height: 200px;
    background: skyblue;
    position: absolute;

    /*關鍵代碼*/
    animation: my-css 5s 2;
    animation-fill-mode: forwards;

}
相關文章
相關標籤/搜索