CSS动画 -- transition 和 animation

动画1
动画2
弹跳实例:Bounce Sample

css动画

1. css transition (隐式动画)

可设定两个状态之间的平滑过渡

可指定的属性

  • transition-delay 变化发生的延迟时间
  • transition-duration 变化发生的持续时间
  • transition-property 在指定属性上应用transition设定
  • transition-time-function 指定变化发生的速度(默认为ease)

示例(hover动画)

  • 未设置动画

    .item {
      height: 60px;
      width: 30px;
      background: grey;
      margin: 10px;
    }
    
    .item:hover{
      height: 150px;
      width: 150px;
      background: green;
    }
    
  • 设置transition

    t1
    t2
    .t1{
      /* 设置所有属性在1s内加速变化 */
      transition: 1s all ease-in;
    }
    
    .t2{
        /* 高和颜色在1s内变化, 之后宽度变化*/
        transition: 1s height ease-in,
                    1s 1s width cubic-bezier(.17,.67,.83,.67),
                    1s background;
    }
    

事件: transitionend

  • 在css完成过渡时触发
  object.addEventListener('transitionend', function(){
    // do something
  })

问题

  • 需要事件触发:如hover,自定义class的增加等。
  • 一次性,无法重复使用,除非一再触发。
  • 只有两个状态,没有中间状态。
  • 对多个属性变化的支持不够。
  • 支持设定的属性有限。(参考:animatable

2. CSS Animation

通过指定关键帧 @keyfrmaes 来设计动画。

  • 支持多个中间状态(使用百分比设定)
  • 可设置重复次数: n次或无数次
  • 可设定动画结束时的元素状态: animation-fill-mode
  • animation-direction: 可设定动画播放时状态变化的顺序

可设定的属性

  • animation-name: 动画名称
  • animation-duration: 持续时间;
  • animation-timing-function: 变化发生的速度; (可指定steps函数)
    • 时间函数可以应用于整个动画中,也可以应用于关键帧的某两个百分比之间
  • animation-delay: 变化发生的延迟时间;
  • animation-fill-mode: 结束状态; (none | forwards | backwards | both)
  • animation-direction: 状态变化的顺序; (normal | reverse | alternate |alternate-reverse)
  • animation-iteration-count: 动画重复次数(infinite-无限次);
  • animation-play-state: 动画突然中止时的状态(如hover动画中鼠标移除)(paused | running)(无法简写)

@keyframes 定义动画的各个状态(关键帧)

  • 与animation-name相对应
  • 使用百分比设定中间状态(from与0%相同, to与100%相同)

事件

  1. animationstart - 动画开始时触发
  2. animationiteratoin - 动画重复播放时
  3. animationend - 动画完成后触发

简单示例

a1
a2
.a1{    animation: anime1 2s infinite;  }
.a2{    animation: rainbow 6s infinite, resize 2s infinite;  }  
.anime:hover{    animation-play-state: paused;  }

@keyframes anime1{
  from, to { background: yellow; height: 50px; }
  50% { background: orange; height: 20px;}
}

@keyframes rainbow{
  0% { background: red; }
  20% { background: orange; }
  40% { background: yellow; }
  60% { background: green; }
  80% { background: blue; }
  100% { background: purple; }
}

示例 bounce

Bounce Sample
@keyframes bounce {
  from, 20%, 53%, to { 
    transform: translate3d(0, 0 ,0); 
    opacity: 1;
  }
  40%, 43% { 
    transform: translate3d(0, -30px, 0) scaleY(1.2);
    opacity: 0.6;
  }
  70% {
    transform: translate3d(0, -15px, 0) scaleY(1.1);
    opacity: 0.8;
  }
  80% { 
    transform: translate3d(0, 0, 0) scaleY(0.9);
    opacity: 0.9;
  }
}
posted @ 2021-08-12 15:36  朝日asahi  阅读(115)  评论(0编辑  收藏  举报