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

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


เอฟเฟกต์ Pulse

องค์ประกอบขยาย-ย่อซ้ำๆ คล้ายการเต้นของหัวใจ ใช้สำหรับดึงดูดความสนใจ loading indicator หรือ notification badge

โค้ดตัวอย่างสมบูรณ์

<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 pulse {
      0%   { -webkit-transform: scale(1); }
      50%  { -webkit-transform: scale(1.1); }
      100% { -webkit-transform: scale(1); }
    }
    @keyframes pulse {
      0%   { transform: scale(1); }
      50%  { transform: scale(1.1); }
      100% { transform: scale(1); }
    }

    .pulse {
      -webkit-animation-name: pulse;
      animation-name: pulse;
    }
  </style>
</head>
<body>
  <div id="animated-example" class="animated pulse"></div>
  <button onclick="myFunction()">Reload page</button>
  <script>
    function myFunction() { location.reload(); }
  </script>
</body>
</html>

การวิเคราะห์

ขั้นตอนScaleพฤติกรรม
0%1.0ขนาดปกติ
50%1.1ขยาย 10% (เต้น)
100%1.0กลับสู่ปกติ

เวเรียนท์ Pulse ที่นิยมใช้งาน

Pulse แบบเร็ว (Heartbeat)

.pulse-fast {
  animation: pulse 0.5s ease-in-out infinite;
}

Pulse แบบนุ่มนวล (Breathing)

@keyframes breathe {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.05); }
}
.breathe { animation: breathe 3s ease-in-out infinite; }

Pulse พร้อม Box Shadow (Glow)

@keyframes pulse-glow {
  0%, 100% { 
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.7);
  }
  50% { 
    transform: scale(1.05);
    box-shadow: 0 0 20px 10px rgba(255, 107, 107, 0);
  }
}
.pulse-glow { animation: pulse-glow 2s ease-out infinite; }

Notification Badge

.badge {
  animation: pulse 1.5s ease-in-out infinite;
  transform-origin: center;
}