HTML\CSS实现动画效果
一、CSS动画
1. CSS的2D转换
CSS转换包括移动、旋转、缩放和倾斜元素。
1.1 移动
translate()方法从其当前位置移动指定,向右、向下为正方向。
/*将div元素向右、向下移动50个像素*/
div{
transform:translate(50px,50px)
}
1.2 旋转
rotate() 方法根据给定的角度顺时针或逆时针旋转元素,顺时针为正。
/*将div元素顺时针旋转20度*/
div {
transform: rotate(20deg);
}
1.3 缩放
scale() 方法根据给定的宽度和高度参数增加或减少元素的大小。`
/*将div元素增大为其原始宽度的两倍和其原始高度的三倍*/
div {
transform: scale(2, 3);
}
2. CSS动画效果
2.1 @keyframes规则
如果在 @keyframes 规则中指定了 CSS 样式,动画将在特定时间逐渐从当前样式更改为新样式。要使动画生效,必须将动画绑定到某个元素。
/*将 "example" 动画绑定到 < div > 元素。动画将持续 4 秒钟,同时将 < div> 元素的背景颜色从 "red" 逐渐改为 "yellow"*/
/* 动画代码 */
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
/* 向此元素应用动画效果 */
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
2.2 延迟动画
animation-duration属性定义动画完成一个周期所需要的时间,以秒或毫秒为单位
/*time默认为0,意味着没有动画效果*/
animation-duration: time;
2.3 设置动画运行次数
animation-iteration-count 属性定义动画的播放次数。
/*n默认为1,infinite规定动画应该无限次播放*/
animation-iteration-count: n|infinite;
2.4 指定动画的速度曲线
animation-timing-function 规定动画的速度曲线,速度曲线定义动画从一套 CSS 样式变为另一套所用的时间。速度曲线用于使变化更为平滑。
animation-timing-function: value;
值 | 描述 |
---|---|
linear | 动画从头到尾速度是相同的 |
ease | 默认值。动画以低俗开始,然后加快,在结束前变慢 |
ease-in | 动画以低俗开始 |
ease-out | 动画以低速结束 |
ease-in-out | 动画以低速开始和结束 |
2.5 指定动画的填充模式
CSS 动画不会在第一个关键帧播放之前或在最后一个关键帧播放之后影响元素。animation-fill-mode 属性能够覆盖这种行为。在不播放动画时,animation-fill-mode 属性规定目标元素的样式。
animation-fill-mode 属性可接受以下值:
值 | 描述 |
---|---|
none | 默认值,动画在执行之前或之后不会对元素应用任何样式 |
forwards | 元素将保留由最后一个关键帧设置的样式值,依赖animation-direction 和 animation-iteration-count |
backwards | 元素将获取由第一个关键帧设置的样式值(取决于 animation-direction),并在动画延迟期间保留该值 |
both | 动画会同时遵循向前和向后的规则,从而在两个方向上扩展动画属性 |
/* < div> 元素在动画结束时保留来自最后一个关键帧的样式值*/
div {
width: 100px;
height: 100px;
background: red;
position: relative;
animation-name: example;
animation-duration: 3s;
animation-fill-mode: forwards;
}
二、动画效果实例
1. 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动画制作</title>
</head>
<body>
<div id="fst">
<div id=snd></div>
</div>
<style>
#fst{
background: antiquewhite;
margin: auto;
width: 600px;
height: 600px;
}
#snd{
background:rgb(241, 115, 168);
animation: move 5s infinite alternate ;
width: 100px;
height: 100px;
}
@keyframes move {
0%{
transform: translate(0,250px);
}
50%{
transform: translate(250px,250px);
background: rgb(255, 123, 0);
border-radius: 50%;
}
100%{
transform: translate(500px,250px);
background: rgb(59, 116, 201);
}
}
</style>
</body>
</html>
2. 结果
初始状态:
中间状态:
最终状态: