css3新增属性@keyframes(关键帧)
,可以帮助开发者不必依赖JavaScript,只使用css代码完成动画制作
那么如何使用@keyframes呢?
这里有两个重要知识点:
1.@keyframes 定义关键帧
- 语法:
@keyframes 两帧动画名称 { from {top:0px;} to {top:200px;} }
@keyframes 多帧动画名称 { 0% { transform: translate(100px, 0); } 50% {transform: translate(200px, 200px); } 100%{ transform: translate(0, 100px); } }
动画内可以任意自定义合法的 CSS 样式属性
/*两帧*/
@keyframes mymove
{
from {top:0px;}/*第1帧*/
to {top:200px;}/*第2帧*/
}
/*多帧*/
@keyframes mymove {
/*第1帧*/
0% {
transform: translate(100px, 0);
}
/*第2帧*/
25% {
transform: translate(200px, 0);
}
/*第3帧*/
50% {
transform: translate(200px, 200px);
}
/*第4帧*/
75% {
transform: translate(0px, 200px);
}
/*第5帧*/
100% {
transform: translate(0, 100px);
}
}
2. animation 使用帧动画
animation-name
: 动画名称 (必须)
animation-duration
: 动画运行时间(必须)
animation-timing-function
: 动画运行方式速度曲线 如:linear ,ease ,ease-in.ease-out,ease-in-out
animation-delay
: 动画延时时间
animation-iteration-count
: 动画播放次数填写数字,如果是 infinite
:一直播放
animation-direction
: 动画下一周期轮流反向播放动画 ,默认是normal
。alternate
:动画轮流反转播放
animation-play-state
: 指定动画是否正在运行或已暂停, paused
:停止 。running
:运行
animation-fill-mode
: 规定当动画不播放时(当动画完成时,或当动画有一个延迟未开始播放时),动画状态。
none
:不改变默认状态。
forwards
:保持最后一帧(最后一帧中定义),
backwards
:在animation-delay
所指定的一段时间内。动画开始之前,应用开始属性也就是起始位置在第一帧的位置(第一帧中定义)
both
: forwards
,backwards
属性都被应用
综合方式暂时不受填写顺序影响
,按照习惯应该如上的流程填写属性
.container{
width: 200px;
height: 200px;
/*单独定义*/
background-color: yellow;
/*动画名称 (必须)*/
animation-name: mymove;
/*动画运行时间(必须)*/
animation-duration: 10s;
/*动画运行方式速度曲线*/
animation-timing-function: linear;
/*动画延时时间*/
animation-delay: 2s;
/*动画播放次数*/
animation-iteration-count: 1;
/*动画下一周期轮流反向播放动画*/
animation-direction: alternate;
/*指定动画是否正在运行或已暂停。*/
animation-play-state: running;
/*规定当动画不播放时(当动画完成时,或当动画有一个延迟未开始播放时),动画状态。*/
animation-fill-mode: both;
/*综合定义*/
animation: mymove 10s infinite both ease 2s alternate;
/*名称和时间必须定义*/
animation: mymove 10s ;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
@keyframes boxmove {
0% {
transform: translate(100px, 0);
}
25% {
transform: translate(200px, 0);
}
50% {
transform: translate(200px, 200px);
}
75% {
transform: translate(0px, 200px);
}
100% {
transform: translate(0, 100px);
}
}
.box {
width: 200px;
height: 200px;
background-color: yellow;
animation: boxmove 10s linear;
animation-name: boxmove;
animation-duration: 10s;
animation-timing-function: linear;
animation-delay: 2s;
animation-iteration-count: 1;
animation-direction: alternate;
animation-play-state: running;
animation-fill-mode: both;
animation: boxmove 10s both ease 2s alternate infinite;
}
</style>
</head>
<body>
<div class="box" id="box"></div>
</body>
</html>