เอฟเฟกต์ Shake
องค์ประกอบสั่นซ้าย-ขวา คล้ายการสั่นหัว "ไม่" หรือ error state ใช้ translateX สลับเครื่องหมาย
โค้ดตัวอย่างสมบูรณ์
<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: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes shake {
0%, 100% { -webkit-transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { -webkit-transform: translateX(-10px); }
20%, 40%, 60%, 80% { -webkit-transform: translateX(10px); }
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }
20%, 40%, 60%, 80% { transform: translateX(10px); }
}
.shake {
-webkit-animation-name: shake;
animation-name: shake;
}
</style>
</head>
<body>
<div id="animated-example" class="animated shake"></div>
<button onclick="myFunction()">Reload page</button>
<script>
function myFunction() { location.reload(); }
</script>
</body>
</html>
การวิเคราะห์ Keyframes
| ขั้นตอน | Transform X | ทิศทาง |
|---|---|---|
| 0% | 0 | เริ่มต้น |
| 10% | -10px | ซ้าย |
| 20% | +10px | ขวา |
| 30% | -10px | ซ้าย |
| 40% | +10px | ขวา |
| 50% | -10px | ซ้าย |
| 60% | +10px | ขวา |
| 70% | -10px | ซ้าย |
| 80% | +10px | ขวา |
| 90% | -10px | ซ้าย |
| 100% | 0 | กลับสู่กึ่งกลาง |
เวเรียนท์ Shake ที่นิยม
Shake แนวตั้ง (Vertical Shake)
@keyframes shakeY {
0%, 100% { transform: translateY(0); }
10%, 30%, 50%, 70%, 90% { transform: translateY(-5px); }
20%, 40%, 60%, 80% { transform: translateY(5px); }
}
Shake 3D (Rotate)
@keyframes shake3d {
0%, 100% { transform: rotate(0deg); }
10%, 30%, 50%, 70%, 90% { transform: rotate(-5deg); }
20%, 40%, 60%, 80% { transform: rotate(5deg); }
}
Shake + Opacity (จางขณะสั่น)
@keyframes shake-fade {
0%, 100% { transform: translateX(0); opacity: 1; }
50% { transform: translateX(-10px); opacity: 0.5; }
}
การใช้งานจริง: Form Validation
.input-error {
animation: shake 0.4s ease-in-out;
border-color: #ff6b6b;
}
.input-error:focus {
animation: none; /* หยุดสั่นตอนพิมพ์ */
}
Performance Tip
ใช้ transform: translateX() แทน left/right เพื่อ GPU acceleration และไม่ trigger layout/reflow