要在CSS中创建动画,我们可以使用animation属性。该属性允许我们指定动画的关键帧、持续时间、时间函数、延迟和迭代次数。
以下是对各个属性的介绍:
- animation-name: 指定要应用于元素的动画名称。
- animation-duration: 指定动画的持续时间。
- animation-timing-function: 指定动画的时间函数,用于控制动画的速度。
- animation-delay: 指定动画的延迟时间,即动画开始之前的等待时间。
- animation-iteration-count: 指定动画的迭代次数,可以是一个数字或infinite。
- animation-direction: 指定动画的播放方向,可以是normal、reverse、alternate或alternate-reverse。
- animation-fill-mode: 指定动画在播放前和播放后如何应用样式,可以是none、forwards、backwards或both。
- animation-play-state: 指定动画的播放状态,可以是running或paused。
以下是一个简单的例子:
<style> @keyframes example { 0% { background-color: red; } 25% { background-color: yellow; width: 150px; } 75% { background-color: green; width: 200px; } 100%{ background-color: red; } } .box { width: 100px; height: 100px; animation-name: example; animation-duration: 4s; animation-timing-function: ease-out; animation-delay: 1s; animation-iteration-count: infinite; } </style> <div class="box"></div><style>
/* 添加一个过渡效果 */
.box {
width: 100px;
height: 100px;
transition: all 2s ease-in 1s;
}
/* 鼠标悬停时改变宽度 */
.box:hover {
width: 200px;
height: 200px;
transform: rotate(180deg);
opacity: 0.5;
}
@keyframes example {
0% {
background-color: red;
}
25% {
background-color: yellow;
width: 150px;
}
75% {
background-color: green;
width: 200px;
}
100%{
background-color: red;
}
}
.box {
width: 100px;
height: 100px;
animation-name: example;
animation-duration: 4s;
animation-timing-function: ease-out;
animation-delay: 1s;
animation-iteration-count: infinite;
}
</style>
<div class="box"></div>
这个css动画包含了animation的常用属性,仔细观察可以了解到各个属性的含义,修改其属性值,观察盒子模型的动画的变化有助于了解这些属性的含义。