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

วิธีสร้างเอฟเฟกต์ Shake/Wiggle (สั่น/สะดุด) รูปภาพด้วย CSS Animation

ใช้ CSS @keyframes และ animation สร้างเอฟเฟกต์รูปภาพสั่น (Shake) เมื่อ Hover

ตัวอย่างโค้ด

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> img{    width: 400px;    height: 400px;    margin:50px; } img:hover {    animation: shakeImg 0.5s;    animation-iteration-count: infinite; } @keyframes shakeImg {    0% { transform: translate(1px, 1px) rotate(5deg); }    20% { transform: translate(-3px, 0px) rotate(10deg); }    30% { transform: translate(3px, 2px) rotate(-10deg); }    50% { transform: translate(-1px, 2px) rotate(-20deg); }    70% { transform: translate(3px, 1px) rotate(-25deg); }    90% { transform: translate(1px, 2px) rotate(10deg); }    100% { transform: translate(1px, -2px) rotate(-10deg); } } </style> </head> <body> <h1>Hover over the image to shake it<h1> <img src="https://i.picsum.photos/id/551/400/400.jpg"> </body> </html>

คำอธิบาย Animation

  • animation: shakeImg 0.5s infinite; - วนลูปไม่รอจบ 0.5 วินาที/รอบ
  • @keyframes shakeImg - กำหนดตำแหน่ง/หมุน ที่ Keyframes ต่างๆ (0%, 20%, 30%...)
  • transform: translate(x, y) rotate(deg) - ย้าย + หมุน พร้อมกัน
  • ค่าสลับ +/- สร้างความรู้สึก "สั่น"

ปรับแต่งได้

  • Duration: 0.3s (เร็ว), 1s (ช้า)
  • Intensity: translate ±5px, rotate ±30deg (เขตมากขึ้น)
  • Timing Function: ease-in-out, cubic-bezier(...)
  • Trigger: :hover, :focus, :active, หรือ Class .shake (JS Toggle)

Performance Note

ใช้ transform และ opacity เท่านั้น (GPU Accelerated) ไม่ใช้ left/top/width/height -> Smooth 60fps

ผลลัพธ์

รูปภาพ 400x400 Hover -> สั่น/หมุน รอบละ 0.5 วินาที วนลูปไม่รอจบ