Thuộc tính animation-iteration-count
animation-iteration-count xác định **số lần animation lặp lại**. Mặc định là `1` (chạy một lần).
Các giá trị
| Giá trị | Ý nghĩa |
|---|---|
1 (mặc định) | Chạy 1 lần |
<number> | Số lần cụ thể (có thể thập phân: 2.5) |
infinite | Lặp vô hạn |
Ví dụ: Lặp 3 lần
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 150px;
height: 200px;
position: relative;
background-color: yellow;
animation-name: myanim;
animation-duration: 2s;
animation-direction: alternate-reverse;
animation-iteration-count: 3; /* Lặp 3 lần */
}
@keyframes myanim {
from { left: 100px; }
to { left: 200px; }
}
#demo1 { animation-timing-function: ease; }
#demo2 { animation-timing-function: ease-in; }
</style>
</head>
<body>
<div id="demo1">ease effect</div>
<div id="demo2">ease-in effect</div>
</body>
</html>
Giải thích ví dụ
- Mỗi chu kỳ: 2s (thuận) + 2s (nghịch do alternate-reverse) = 4s.
- 3 chu kỳ = 12s tổng cộng.
- Với `alternate-reverse`: Chu kỳ 1 nghịch, 2 thuận, 3 nghịch.
Số lần lặp thập phân
animation-iteration-count: 2.5;
/* Chạy 2 chu kỳ đầy đủ + nửa chu kỳ thứ 3 (dừng ở 50% keyframes) */
Kết hợp với animation shorthand
animation: myanim 2s ease-in-out 0s 3 alternate-reverse forwards;
/* name dur timing delay count direction fill-mode */
Performance & Best Practice
- Infinite: Luôn dùng `will-change: transform, opacity` cho animation vô hạn.
- Pause/Resume: Dùng `animation-play-state: paused | running` thay vì gán iteration-count = 0.
- Reduced motion: Tôn trọng `
@media (prefers-reduced-motion: reduce)` - set `iteration-count: 1` hoặc `animation: none`.
Lưu ý
Nếu `animation-duration: 0s`, iteration-count vô nghĩa. Animation không chạy.