css的过渡transition和动画animation

过渡

过渡(transition)是CSS3中具有颠覆性的特性之一,我们可以在不使用Flash动画或JavaScript的情况下,当元素从一种样式变换为另一种样式时元素添加效果。

过渡动画:是从一个状态渐渐的过渡到另一个状态。低版本浏览器不支持,但是不影响页面布局。经常和:hover一起搭配使用。

属性描述取值范围
transition-property应用过渡效果的 CSS 属性名CSS属性都可以(all, width, color ...)
transition-duration过渡效果持续时间秒和毫秒都可以, 1s 1000ms ...
transition-timing-function过渡效果展示方式linear(匀速), ease(开始慢、中间快、结束慢,默认可省略)
transition-delay过渡效果延迟时间秒和毫秒都可以, 1s 1000ms ...
<style>
  div{
    width: 200px;
   height: 100px;
    background-color: pink;
    transition: width 1s ease 0s,height 2s ease 1s;
    // transition:要过渡的属性    花费的时间   运动曲线    何时开始;
      
    transition-property: width;
    transition-duration: 1s;
    transition-timing-function: linear;
    transition-delay: 2s;
    /* Safari */
    -webkit-transition-property: width;
    -webkit-transition-duration: 1s;
    -webkit-transition-timing-function: linear;
    -webkit-transition-delay: 2s;
  }
  div:hover{
    width:400px;
  }
</style>
//完整代码块

<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <title>过渡</title>
</head>
<style type="text/css">
  div {
    float: left;
    margin-right: 10px;
    width: 200px;
    height: 200px;
    text-align: center;
    line-height: 200px;
    background-color: skyblue;
  }
 
  /* 鼠标悬停时改变盒子颜色 */
  div:hover {
    background-color: aqua;
    transition: all .8s linear 0s;
  }
</style>
<body>
<div></div>
</body>
</html>

动画

动画(animation)是使元素从一种样式逐渐变化为另一种样式的效果。

您可以改变任意多的样式任意多的次数。

请用百分比来规定变化发生的时间,或用关键词 "from" 和 "to",等同于 0% 和 100%。

0% 是动画的开始,100% 是动画的完成。

为了得到最佳的浏览器支持,您应该始终定义 0% 和 100% 选择器。

描述
animation-name规定需要绑定到选择器的 keyframe 名称。。
animation-duration规定完成动画所花费的时间,以秒或毫秒计。
animation-timing-function规定动画的速度曲线。
animation-delay规定在动画开始之前的延迟。
animation-iteration-count规定动画应该播放的次数。
animation-direction规定是否应该轮流反向播放动画。
animation-play-state规定动画是否正在运行或暂停。默认是 "running"。
animation-fill-mode规定对象动画时间之外的状态。
/* 动画代码 */
@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}

/* 向此元素应用动画效果 */
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}
// 完整代码块
<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <title>animation</title>
</head>
<style type="text/css">
  div {
    float: left;
    margin-right: 10px;
    width: 200px;
    height: 200px;
    text-align: center;
    line-height: 200px;
    background-color: skyblue;
    position: absolute;
    border-radius: 50%;
  }

  div {
    animation: myfirst 5s linear 2s infinite alternate;
  }

  @keyframes myfirst {
    0%   {background: red; left:0px; top:0px;}
    25%  {background: yellow; left:200px; top:0px;}
    50%  {background: blue; left:200px; top:200px;}
    75%  {background: green; left:0px; top:200px;}
    100% {background: red; left:0px; top:0px;}
  }

</style>
<body>
<div></div>
</body>
</html>