Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Thuộc tính CSS animation-direction

animation-direction: Điều khiển chiều chạy animation

Thuộc tính animation-direction xác định animation chạy **thuận, nghịch, hay luân phiên**. Mặc định là `normal` (chạy từ 0% → 100%).

Các giá trị

Giá trịHành viMô tả
normal0% → 100%Mặc định, chạy thuận mỗi chu kỳ
reverse100% → 0%Chạy ngược mọi chu kỳ
alternate0%→100% → 0%→100%...Luân phiên: chu kỳ lẻ thuận, chẵn nghịch
alternate-reverse100%→0% → 100%→0%...Luân phiên ngược: chu kỳ lẻ nghịch, chẵn thuận

Ví dụ: reverse

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      width: 150px;
      height: 200px;
      background-color: yellow;
      animation-name: myanim;
      animation-duration: 2s;
      animation-direction: reverse;  /* Chạy ngược: từ to → from */
    }
    @keyframes myanim {
      from { background-color: green; }
      to { background-color: blue; }
    }
  </style>
</head>
<body>
  <div></div>
  <p>Animation chạy từ xanh lam (to) → xanh lá (from) vì reverse.</p>
</body>
</html>

Ví dụ: alternate (luân phiên)

div {
  animation-direction: alternate;
  animation-iteration-count: 3;
  /* Chu kỳ 1: 0%→100% (green→blue)
     Chu kỳ 2: 100%→0% (blue→green)
     Chu kỳ 3: 0%→100% (green→blue) */
}

Kết hợp với timing function

Khi dùng `alternate`/`alternate-reverse`, **timing function cũng bị đảo ngược** ở chu kỳ nghịch.

animation-timing-function: ease-in;  /* Chu kỳ thuận: ease-in */
animation-direction: alternate;
/* Chu kỳ nghịch: tự động thành ease-out */

Ứng dụng thực tế

  • alternate: Loading pulse, heartbeat, breathing effect.
  • reverse: Undo animation, return to start state.
  • alternate-reverse: Bắt đầu từ trạng thái cuối (ví dụ menu đã mở, close trước).

Lưu ý

animation-direction không ảnh hưởng đến animation-fill-mode: forwards - forwards luôn giữ trạng thái keyframe cuối cùng của chu kỳ cuối (tùy direction).