css3 animation动画

css animation面试问题:

写个动画,一个盒子,开始时缩放是 0,50%时是 1,100%时是 0,开始结束都是慢速,持续 2 秒,延迟 2 秒,结束后固定在结束的效果

以上一个问题,把animation的基础用法都考到了,下面一步步解析

  1. 定义盒子
1
2
3
4
5
.box {
width: 120px;
height: 120px;
background-color: burlywood;
}
  1. 定义动画(开始时缩放是 0,50%时是 1,100%时是 0)
1
2
3
4
5
@keyframes scale {
0% { transform: scale(0); }
50% { transform: scale(1); }
100% { transform: scale(0); }
}
  1. 定义动画名称
1
animation-name: scale;
  1. 定义动画运动曲线(开始结束都是慢速)
1
animation-timing-function: ease;

注:这儿也可以用 ease-in-out

easeease-in-out 区别:

ease:开始很慢,但是很快就加速到一个比较大的速度,时间过半就开始缓慢减速,直到最后减速为0;

ease-in-out:开始慢,但是匀加速到一个速度大概时间到1/3的时候就保持这个速度直到最后1/3时间再均匀减速。

参考文章:https://www.bilibili.com/read/cv11269464/

  1. 定义动画运行时间(持续 2 秒)
1
animation-duration: 2s;
  1. 定义动画延迟时间(延迟 2 秒)
1
animation-delay: 2s;
  1. 定义动画填充模式(结束后固定在结束的效果)
1
animation-fill-mode: both;

个人理解both含义:动画开始时应用 @keyframes 0% 状态,动画结束时应用 @keyframes 100% 状态

参考文章:https://www.w3school.com.cn/cssref/pr_animation-fill-mode.asp

  1. 这儿没提到动画次数,可以直接定义1次即可,毕竟题目考到了动画结束状态
1
animation-iteration-count: 1;

使用 animation 简写以上属性值

1
animation: scale ease 2s 1 both 2s;

完整 css

1
2
3
4
5
6
7
8
9
10
11
.box {
width: 120px;
height: 120px;
background-color: burlywood;
animation: scale ease 2s 1 both 2s;
}
@keyframes scale {
0% { transform: scale(0); }
50% { transform: scale(1); }
100% { transform: scale(0); }
}

效果:

animation其他属性

animation-play-state 控制动画是否暂停(paused|running)

animation-direction 控制动画是否反向播放动画(normal|alternate)。alternate表示奇数次正常运动,偶数次反向运动(反向运动表示动画从100%->0%运动)

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2022-01-07/css3-animation/

如果您觉得文章不错,可以点击文章中的广告支持一下!