在 CSS 中,设置元素的动画重复次数是通过 `animation-iteration-count` 属性来实现的。这个属性允许你指定动画应该播放的次数,它可以接受一个整数或 `infinite` 值。
一、整数重复次数
当你指定一个整数作为 `animation-iteration-count` 的值时,动画将按照指定的次数进行播放。例如,如果你设置 `animation-iteration-count: 3;`,动画将播放 3 次然后停止。
以下是一个简单的示例,展示如何使用整数重复次数设置一个元素的动画:
```css
.box {
width: 100px;
height: 100px;
background-color: blue;
animation: bounce 2s ease-in-out infinite;
}
@keyframes bounce {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-20px);
}
100% {
transform: translateY(0);
}
}
```
在上述代码中,`.box` 类的元素具有一个名为 `bounce` 的动画,它在 2 秒内以 `ease-in-out` 缓动效果在垂直方向上上下弹跳。`animation-iteration-count: infinite;` 使动画无限循环播放。如果你将 `infinite` 替换为一个整数,例如 `3`,动画将播放 3 次然后停止。
二、`infinite` 值
当你将 `animation-iteration-count` 设置为 `infinite` 时,动画将无限循环播放,直到元素被移除或动画被停止。这对于创建循环播放的动画效果非常有用,例如滚动条的滚动动画或加载指示器的动画。
以下是一个使用 `infinite` 值设置动画的示例:
```css
.circle {
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
animation: rotate 2s linear infinite;
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
```
在这个例子中,`.circle` 类的元素具有一个名为 `rotate` 的动画,它在 2 秒内以线性缓动效果顺时针旋转 360 度,并无限循环播放。
三、动态设置重复次数
除了在 CSS 中静态地设置动画的重复次数,你还可以使用 JavaScript 来动态地更改 `animation-iteration-count` 属性的值。这使得你可以根据用户交互或其他条件来控制动画的播放次数。
以下是一个使用 JavaScript 动态设置动画重复次数的示例:
```html
.box {
width: 100px;
height: 100px;
background-color: green;
animation: move 2s linear infinite;
}
@keyframes move {
from {
transform: translateX(0);
}
to {
transform: translateX(200px);
}
}
// 获取元素和按钮
const box = document.querySelector('.box');
const button = document.querySelector('button');
// 点击按钮时更改动画重复次数
button.addEventListener('click', function () {
const currentCount = parseInt(window.getComputedStyle(box).getPropertyValue('animation-iteration-count'));
const newCount = currentCount === 1? 3 : 1;
box.style.animationIterationCount = newCount;
});
```
在这个示例中,当用户点击按钮时,JavaScript 代码获取 `.box` 元素的当前 `animation-iteration-count` 值,并根据当前值切换为 1 次或 3 次。然后,通过将新的重复次数设置为 `box.style.animationIterationCount`,动画的重复次数将被动态更改。
`animation-iteration-count` 属性是 CSS 中用于设置元素动画重复次数的重要属性。你可以使用整数指定具体的播放次数,或使用 `infinite` 值使动画无限循环播放。通过 JavaScript 可以动态地更改动画的重复次数,以实现更灵活的动画效果控制。