css动画

114 阅读2分钟

CSS Transition

transition是以下这4个属性的简称

  • transition-property

  • transition-duration

  • transition-timing-function

    • ease 默认值,逐渐放慢
    • linear 匀速
    • ease-in  加速
    • ease-out 减速
    • ease-in-out 先加速后减速
    • cubic-bezier(n,n,n,n) 自定义速度模式
  • transition-delay delay的真正意义在于,它指定了动画发生的顺序,使得多个不同的transition可以连在一起,形成复杂效果。

How to Use CSS Transitions?

To create a transition effect, you must specify two things:

  • the CSS property you want to add an effect to
  • the duration of the effect

Note:  If the duration part is not specified, the transition will have no effect, because the default value is 0.

Transition + Transformation

div {
  width: 100px;
  height: 100px;
  background: red;
  transition: width 2s, height 2s, transform 2s;
}

div:hover {
  width: 300px;
  height: 300px;
  transform: rotate(180deg);
}

transition的局限

transition的优点在于简单易用,但是它有几个很大的局限。

(1)transition需要事件触发,比如hover,click;所以没法在网页加载时自动发生。

(2)transition是一次性的,不能重复发生,除非一再触发。

(3)transition只能定义开始状态和结束状态,不能定义中间状态,也就是说只有两个状态。

(4)一条transition规则,只能定义一个属性的变化,不能涉及多个属性。

CSS Animation就是为了解决这些问题而提出的。

CSS  Transforms

CSS 2D Transforms

  • transform Applies a 2D or 3D transformation to an element

    • translate() 移动
    • rotate() 旋转
    • scaleX()
    • scaleY()
    • scale() 放大或缩小一个元素的size
    div {
    margin: 150px;
    width: 200px;
    height: 100px;
    background-color: yellow;
    border: 1px solid black;
    transform: scale(0.5,0.5);
    }
    
    • skewX()
    • skewY()
    • skew() 斜切
    • matrix()
  • transform-origin

Allows you to change the position on transformed elements

CSS 3D Transforms

CSS Animation

  • @keyframes
  • animation-name
  • animation-duration
  • animation-delay
  • animation-iteration-count 规定动画应该播放的次数
  • animation-direction
    • normal 默认值
    • reverse
    • alternate
    • alternate-reverse
  • animation-timing-function
    • ease 默认值
    • linear 
    • ease-in 
    • ease-out
    • ease-in-out 
    • cubic-bezier(n,n,n,n) 
  • animation-fill-mode
    • none 默认值 回到动画没开始时的状态。
    • forwards 让动画回到最后一帧的状态。
    • backwards 让动画回到第一帧的状态。
    • both 根据animation-direction(见后)轮流应用forwards和backwards规则。
  • animation
定义动画
@keyframes example {
  0%   {background-color:red; left:0pxtop:0px;}
  25%  {background-color:yellow; left:200pxtop:0px;}
  50%  {background-color:blue; left:200pxtop:200px;}
  75%  {background-color:green; left:0pxtop:200px;}
  100% {background-color:red; left:0pxtop:0px;}
}

应用动画
div {
  width100px;
  height100px;
  position: relative;
  background-color: red;
  /* 完整写法 */
  animation-name: example;
  animation-duration5s;
  animation-timing-function: linear;
  animation-delay2s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

 /* 简写 */
div {
  animation: example 5s linear 2s infinite alternate;
}