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

Chỉ định đường cong tốc độ animation với CSS (animation-timing-function)

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 congCảm giácDùng cho
easeChậm-nhanh-chậmTự nhiên nhấtMặc định, UI chung
linearĐềuCơ học, robotSpinner, infinite loop
ease-inChậm → nhanhBị đẩy, rơiModal show, slide in
ease-outNhanh → chậmPhanh, đến đíchModal hide, tooltip
ease-in-outChậm - nhanh - chậm (đậm hơn ease)Mượt, đối xứngCarousel, 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-reverse sẽ đảo ngược timing function khi chạy ngược.