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

สร้างเอฟเฟกต์ Bounce Up (เด้งขึ้น) ด้วย CSS Animation


เอฟเฟกต์ Bounce In Up

เอฟเฟกต์นี้ทำให้องค์ประกอบเด้งขึ้นมาจากด้านล่างพร้อมแอนิเมชัน overshoot (เกินจุดแล้วกลับมา) ใช้เหมาะกับการโชว์ modal, toast, หรือ element เข้ามาบนหน้าจอ

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

<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 bounceInUp {
      0%   { opacity: 0; -webkit-transform: translateY(2000px); }
      60%  { opacity: 1; -webkit-transform: translateY(-30px); }
      80%  { -webkit-transform: translateY(10px); }
      100% { -webkit-transform: translateY(0); }
    }
    @keyframes bounceInUp {
      0%   { opacity: 0; transform: translateY(2000px); }
      60%  { opacity: 1; transform: translateY(-30px); }
      80%  { transform: translateY(10px); }
      100% { transform: translateY(0); }
    }

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

การวิเคราะห์กลไกการเด้ง

ขั้นตอนTransform YOpacityพฤติกรรม
0%+2000px (ล่างจอ)0เริ่มจากด้านล่างนอกหน้าจอ
60%-30px (เกินจุด)1เด้งขึ้นเกินจุดปลายทางเล็กน้อย
80%+10px (กลับมา)1ตกกลับลงมาสักนิด
100%0 (จุดหมาย)1หยุดนิ่งตำแหน่งสุดท้าย

การปรับแต่งสำหรับการใช้งานจริง

.bounceInUp {
  animation-name: bounceInUp;
  animation-duration: 0.6s;  /* เร็วกว่าต้นฉบับมาก */
  animation-timing-function: cubic-bezier(0.68, -0.55, 0.27, 1.55); /* custom bounce */
}