Thuộc tính animation-timing-function
animation-timing-function định nghĩa **đường cong tốc độ** của animation qua các keyframes. Khác với transition (chỉ 2 trạng thái), animation có thể có nhiều keyframes và timing function áp dụng **cho từng đoạn** giữa 2 keyframes.
Cú pháp
animation-timing-function: ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier() | steps();
Áp dụng cho từng keyframe segment
@keyframes myanim {
0% { left: 0; animation-timing-function: ease-out; }
50% { left: 200px; animation-timing-function: ease-in; }
100% { left: 0; }
}
Ví dụ so sánh ease vs ease-in
<!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;
}
@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>
So sánh chi tiết
| Giá trị | Đường cong | Cảm giác | Dùng cho |
|---|---|---|---|
ease | Chậm-nhanh-chậm | Tự nhiên nhất | Mặc định, UI chung |
linear | Đều | Cơ học, robot | Spinner, infinite loop |
ease-in | Chậm → nhanh | Bị đẩy, rơi | Modal show, slide in |
ease-out | Nhanh → chậm | Phanh, đến đích | Modal hide, tooltip |
ease-in-out | Chậm - nhanh - chậm (đậm hơn ease) | Mượt, đối xứng | Carousel, tab |
Steps() - Animation rời rạc
/* Sprite sheet animation - 8 frames */
animation-timing-function: steps(8, end);
/* Typing effect */
animation-timing-function: steps(40, end);
Lưu ý quan trọng
- Timing function mặc định của animation là
ease(khác transition cũng là ease). - Có thể đặt cho toàn bộ animation hoặc từng keyframe segment.
animation-direction: alternate-reversesẽ đảo ngược timing function khi chạy ngược.