美文网首页
CSS3 transition and animation简单理

CSS3 transition and animation简单理

作者: meteornnnight | 来源:发表于2019-06-04 19:33 被阅读0次

讲解得非常好的一篇文章:
css3中的变形(transform)、过渡(transtion)、动画(animation)

transition

CSS中的transition允许css的属性值在一定的时间区间内平滑地过渡。这种效果可以在鼠标单击、获得焦点、被点击或对元素任何改变中触发,并圆滑地以动画效果改变CSS的属性值。
transition这个过程往往是从状态a切换到状态b,所以往往需要类似鼠标移入、点击等事件来触发状态的切换,从而触发transition。
transition: property || duration || time-function || delay

  • property: 不是所有的CSS property都可以实现transition效果。
  • duration: 单位可以是s也可以是ms。
  • timing-function: linear|ease|ease-in|ease-out|ease-in-out|cubic-bezier
  • cubic-bezier(x1,y1,x2,y2),取值都要在[0,1]之间;
  • delay: 决定改变元素属性值后多长时间开始执行transition效果。

一个栗子:

<style>
      div{
            margin: 100px;
            text-align: center;
            width:100px;
            height:100px;
            background: #00f;
            -webkit-transition: all 1s ease .1s;
            -moz-transition: all 1s ease .1s;
            -o-transition: all 1s ease .1s;
            transition: all 1s ease .1s;
        }
        div:hover{
            background: #f00;
            transform: translateX(100px) rotate(45deg);
        }   
</style>

结果:

transition.gif

可以看到颜色过渡和transform过渡是同时进行和完成的,如果想要错开多个过渡,可以利用transition的delay属性。

animation

transition可以看成是两个状态之间的切换,但是对于animation来说,中间会有很多个状态,于是我们引入“keyframes”关键帧,语法如下:

@keyframes "name"{
    from{
      //css rules
    }
    percentage{
      //css rules
    }
    to{
     //css rules
    }
}

然后我们在要应用动画的元素的CSS style中定义animation的几个property:

  • animation-name:keyframes定义的name,
  • animation-duration,
  • animation-timing-function:与transition的六个选项一致
  • animation-delay,
  • animation-iteration-count:动画重复次数
  • animation-direction: normal | alternative
  • animation-play-state: running | paused
    在动画结束之后,元素的CSS style会回到默认样式,动画中定义的CSS样式都会被清除。

一个栗子

        <style>
            @keyframes move {
                from{
                    margin-left: 100px;
                    background-color:pink;
                }
                20% {
                    margin-left: 150px;
                    background: red;
                }
                40% {
                    margin-left: 200px;
                    background-color:purple;
                }
                60% {
                    margin-left: 150px;
                    background-color: red;
                }
                to {
                    margin-left:100px;
                    background-color: pink;
                }
            }
            div{
                width: 100px;
                height: 100px;
                margin-left: 100px;
                text-align: center;
                background:pink;
                animation: move 5s linear;
            }           
        </style>

结果:

animation.gif

嵌套使用animation

嵌套使用animation可以解决两个问题:

  1. 公用动画的抽取
  2. 避免动画的覆盖冲突

相关文章

网友评论

      本文标题:CSS3 transition and animation简单理

      本文链接:https://www.haomeiwen.com/subject/wjqlxctx.html