从此
文章
📄文章 #️⃣专题 🌐上网 📺 🛒 📱

CSS Animation 动画 @keyframes

🕗2019-12-25

动画

CSS过渡(transition)也是属于动画的范围,只不过它只能是开始到过渡这两个点,中间由浏览器去完成,而动画允许开发者一帧一帧的去编码。

@keyframes

要执行的动画都写在这个规则里

my-css是自定义的名字

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

from就是之前的状态,to是之后的状态,嗯,这个其实和过渡没啥区别,这是第一种写法。

然后就是这行代码

animation: my-css 5s;

完整代码

<!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>

这只是单纯一种属性的变化,多种属性的变化是这样的

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

接下来是一帧一帧的完成

@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属性

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;

}