CSS cho phép tạo hoạt ảnh cho các thuộc tính của phần tử. Thuộc tính shorthand animation gộp nhiều thuộc tính con như animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, animation-play-state vào một khai báo duy nhất.
Cú pháp
object.style.animation = "name duration timingFunction delay iterationCount direction fillMode playState"
Các giá trị thành phần
| Thành phần | Mô tả |
|---|---|
| animation-name | Tên keyframe để liên kết với bộ chọn. |
| animation-duration | Thời gian hoàn thành một chu kỳ (giây/ms). |
| animation-timing-function | Đường cong tốc độ (ease, linear, cubic-bezier...). |
| animation-delay | Độ trễ trước khi bắt đầu. |
| animation-iteration-count | Số lần lặp (số hoặc infinite). |
| animation-direction | Hướng chạy: normal, reverse, alternate... |
| animation-fill-mode | Kiểu áp dụng ngoài thời gian chạy (forwards, backwards...). |
| animation-play-state | Trạng thái: running hoặc paused. |
| initial | Đặt về giá trị mặc định. |
| inherit | Kế thừa từ phần tử cha. |
Ví dụ
Ví dụ minh họa cho thuộc tính animation shorthand:
<!DOCTYPE html> <html> <head> <style>
div {
width: 5px;
height: 15px;
background-color: limegreen;
animation: demo 4s infinite;
}
@keyframes demo {
from { width: 5px; background-color: limegreen; }
to { width: 400px; background-color: darkgreen; }
}
@keyframes demo1 {
from { height: 5px; background-color: limegreen; }
to { height: 400px; background-color: darkgreen; }
}
</style>
<script>
function changeAnimation() {
document.getElementById("DIV1").style.animation = "demo1 4s 2";
}
</script> </head>
<body>
<button onclick="changeAnimation()">THAY ĐỔI HOẠT ẢNH</button>
<p>Nhấn nút trên để thay đổi hoạt ảnh dưới</p>
<div id="DIV1"></div>
</body> </html>
Kết quả
Hoạt ảnh ban đầu mở rộng chiều rộng:

Sau khi nhấn nút, chuyển sang hoạt ảnh mở rộng chiều cao (chạy 2 lần):
