浅析css动画的steps()

331 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第8天,点击查看活动详情

前言

之前写过一个广告灯牌效果的文章,使用了steps()实现动画效果,以前都没有接触过,今天来详细了解下相关知识

steps()基本介绍

steps()和cubic-bezier()为css动画中的缓动函数animation-timing-function的属性值。
steps()有两个关键字:step-startstep-end
cubic-bezier()的关键字有lineareaseease-inease-out以及ease-in-out

steps()允许将动画分割成段(一帧一帧的动画效果),而不是从一种状态持续到另一种状态的过渡。

语法:

animation-timing-function : steps(`number_of_steps`, direction)

number_of_steps参数: 是一个正整数,指定动画分割的帧数(整个动画过程分成几步完成)

direction参数:表示动画是从一帧到另一帧的开头连续还是末尾连续

direction参数的取值:
jump-start(start)
jump-end(end),该值为默认值
jump-both
jump-none

演示:
a. 参数值start:在每个时间间隔开始的时候跳1步到下一状态位置

steps(2, start)

image.png
表示一开始,动画执行了一帧

b. end参数:在每个时间间隔结束的时候跳1步到下一状态位置

steps(4, end)

image.png
表示时间一结束,动画就停止

c. jump-none参数:在每个时间间隔开始和结束的时候跳1步到下一状态位置

steps(5, jump-none)

image.png

d. jump-both参数:在每个状态位置停留够一个时间间隔才跳到下一位置

steps(3, jump-both)

image.png

小案例

设置3个元素,表示三种动画,普通动画和其它两种关键帧动画,设置从左边移动到最右边的动画效果。并定义一个刻度元素,平均分成5等分,好对比两种关键帧动画的差异。

<div class="move move-1">no steps</div>
<!-- 把整个动画分成5帧 -->
<div class="move move-2">steps(5, start)</div>
<div class="move move-3">steps(5, end)</div>
<!-- 一个5等分的刻度 -->
<div class="line">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
.move {
  width: 160px;
  padding: 20px 0;
  margin-top: 10px;
  text-align: center;
  color: #fff;
  position: relative;
}
.move-1 {
  animation: move-in-steps 10s  infinite;
}

.move-2 {
  animation: move-in-steps 10s steps(5, start) infinite;
}
.move-3 {
  animation: move-in-steps 10s steps(5) infinite;

}
@keyframes move-in-steps {
  0% {
    left: 0;
    background: #3dc1d3;
  }

  100% {
    left: 100%;
    background: #1e272e;
  }
}

image.png