Giới thiệu
Hiệu ứng Wobble (rung lắc) làm phần tử dao động ngang kết hợp xoay nhẹ, tạo cảm giác "rung động" tự nhiên. Thường dùng cho: notification badge, button lỗi, loading indicator, hoặc thu hút chú ý.
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 wobble {
0% { -webkit-transform: translateX(0%); }
15% { -webkit-transform: translateX(-25%) rotate(-5deg); }
30% { -webkit-transform: translateX(20%) rotate(3deg); }
45% { -webkit-transform: translateX(-15%) rotate(-3deg); }
60% { -webkit-transform: translateX(10%) rotate(2deg); }
75% { -webkit-transform: translateX(-5%) rotate(-1deg); }
100% { -webkit-transform: translateX(0%); }
}
@keyframes wobble {
0% { transform: translateX(0%); }
15% { transform: translateX(-25%) rotate(-5deg); }
30% { transform: translateX(20%) rotate(3deg); }
45% { transform: translateX(-15%) rotate(-3deg); }
60% { transform: translateX(10%) rotate(2deg); }
75% { transform: translateX(-5%) rotate(-1deg); }
100% { transform: translateX(0%); }
}
.wobble {
-webkit-animation-name: wobble;
animation-name: wobble;
}
</style>
</head>
<body>
<div id="animated-example" class="animated wobble"></div>
<button onclick="myFunction()">Tải lại trang</button>
<script>
function myFunction() { location.reload(); }
</script>
</body>
</html>
Phân tích keyframes
Animation diễn ra qua 7 giai đoạn, biên độ dao động giảm dần (damping):
- 0%: Vị trí gốc
- 15%: Lùi 25%, xoay -5°
- 30%: Tiến 20%, xoay +3°
- 45%: Lùi 15%, xoay -3°
- 60%: Tiến 10%, xoay +2°
- 75%: Lùi 5%, xoay -1°
- 100%: Về vị trí gốc
Tùy biến
/* Chậm hơn, rung nhẹ hơn */
.wobble-slow {
animation: wobble 2s ease-in-out;
}
/* Chỉ rung ngang, không xoay */
@keyframes wobble-horizontal {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-10px); }
75% { transform: translateX(10px); }
}
Lưu ý hiệu năng
- Dùng
transform(GPU accelerated) thay vìleft/right - Thêm
will-change: transformnếu animation chạy liên tục - Tránh lồng nhiều animation wobble cùng lúc gây lag