Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

สร้างเอฟเฟกต์ Shake (สั่น) ด้วย CSS Animation


เอฟเฟกต์ 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