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

Tạo hiệu ứng Tada (gật đầu vui vẻ) với CSS

Giới thiệu

Hiệu ứng Tada (từ Animate.css) làm phần tử phóng to/thu nhỏ kết hợp xoay nhẹ qua trái/phải, tạo cảm giác "gật đầu vui vẻ" hoặc "chuông gió". Rất phù hợp cho: notification, achievement badge, call-to-action button, empty state illustration.

Ví dụ hoàn chỉnh

<!DOCTYPE html>
<html>
<head>
  <style>
    .animated {
      background-image: url(/css/images/logo.png);
      background-repeat: no-repeat;
      background-position: left top;
      padding-top: 95px;
      margin-bottom: 60px;
      -webkit-animation-duration: 1s;
      animation-duration: 1s;
      -webkit-animation-fill-mode: both;
      animation-fill-mode: both;
    }

    @-webkit-keyframes tada {
      0%     { -webkit-transform: scale(1); }
      10%, 20% { -webkit-transform: scale(0.9) rotate(-3deg); }
      30%, 50%, 70%, 90% { -webkit-transform: scale(1.1) rotate(3deg); }
      40%, 60%, 80% { -webkit-transform: scale(1.1) rotate(-3deg); }
      100%   { -webkit-transform: scale(1) rotate(0); }
    }

    @keyframes tada {
      0%     { transform: scale(1); }
      10%, 20% { transform: scale(0.9) rotate(-3deg); }
      30%, 50%, 70%, 90% { transform: scale(1.1) rotate(3deg); }
      40%, 60%, 80% { transform: scale(1.1) rotate(-3deg); }
      100%   { transform: scale(1) rotate(0); }
    }

    .tada {
      -webkit-animation-name: tada;
      animation-name: tada;
    }
  </style>
</head>
<body>
  <div id="animated-example" class="animated tada"></div>
  <button onclick="myFunction()">Tải lại trang</button>
  <script>
    function myFunction() { location.reload(); }
  </script>
</body>
</html>

Phân tích keyframes

%ScaleRotateMô tả
0%1.00°Bắt đầu bình thường
10-20%0.9-3°Thu nhỏ, nghiêng trái
30,50,70,90%1.1+3°Phóng to, nghiêng phải (4 lần)
40,60,80%1.1-3°Phóng to, nghiêng trái (3 lần)
100%1.00°Về trạng thái gốc

Tùy biến: Chỉ rung nhẹ (subtle tada)

@keyframes tada-subtle {
  0%, 100% { transform: scale(1) rotate(0); }
  10%, 20% { transform: scale(0.95) rotate(-2deg); }
  30%, 50%, 70% { transform: scale(1.05) rotate(2deg); }
  40%, 60%, 80% { transform: scale(1.05) rotate(-2deg); }
}

.tada-subtle { animation: tada-subtle 0.8s ease-in-out; }

Kích hoạt bằng JavaScript (khuyên dùng)

<button id="btn" class="animated">Click me!</button>
<script>
  const btn = document.getElementById('btn');
  btn.addEventListener('click', () => {
    btn.classList.remove('tada');
    void btn.offsetWidth; // trigger reflow
    btn.classList.add('tada');
  });
</script>

Lưu ý

  • Duration khuyến nghị: 0.8s - 1.2s (10s mặc định quá chậm)
  • Dùng animation-iteration-count để lặp lại: infinite hoặc số lần
  • Kết hợp animation-delay cho hiệu ứng staggered (nhiều element)