【面试】CSS动画之transition和animation属性整理和实例

参考:阮一峰的文章css

CSS实现动画主要有两种方法:transitionanimation属性。html

transition

transition`实例

先看一个transition实现长度拉伸的例子:函数

#transition-demo {
      height: 100px;
      background-color: yellowgreen;
      transition: height 1s 0.5s ease-out; // 定义过渡规则
    }
    #transition-demo:hover {
      height: 200px;
    }
    
<div id="transition-demo">
  transition例子,鼠标悬停试试
</div>
复制代码

transition经常使用属性

  • transition-property: height; // 适用于哪一个属性动画

  • transition-duration: 1s;spa

  • transition-delay: 1s;code

  • transition-time-function: ease/linear/ease-in(加速)/ease-out/cubic-bezier(自定义);orm

transition特性

  1. 须要具体数值,不能用block,none等htm

  2. transition需用事件触发,不能在网页加载时自动发生blog

  3. 一次性,不能重复发生,除非一再触发事件

  4. 只有两个状态:开始和结束状态

  5. 一条transition规则只能定义一个属性

animation

CSS animation就是为了上面这些问题而提出的。animation是一个很是成熟的能够用来展示动画效果的属性。

animation实例

先看一个动画播放颜色渐变、鼠标悬停暂停播放的例子:

#animation-demo {
      height: 200px;
      animation: 3s type forwards alternate infinite; // 动画效果的规则
      animation-play-state: running;
    }

    #animation-demo:hover {
      animation-play-state: paused;
    }

    @keyframes type {
      from {background: yellowgreen}
      50% {background: yellow}
      to {background: aquamarine}
    }
    
<div id="animation-demo">
  animation例子,鼠标悬停试试
</div>
复制代码

animation经常使用属性

  • animation-name: rainbow;

  • animation-duration: 1s;

  • animation-timing-function: ease-in-out;

  • animation-delay: 1s;

  • animation-fill-mode(动画停留在): none(动画没开始时)/forwards(结束)/backwards(第一帧)/both;

  • animation-direction(动画播放方向): normal(正向)/alternate(交替慎用)/reverse(反向)/alternate-reverse(反向交替慎用);

  • animation-iteration-count(播放次数): 3/infinite(无限);

  • steps(10)函数实现分步过渡

  • animation-play-state(用于让动画保持忽然终止时的状态):running(例如悬停时播放)/paused(非悬停时暂停); 注意这个属性不能简写

相关文章
相关标签/搜索