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

กำหนดให้อิลิเมนต์คงค่าสไตล์จาก Keyframe สุดท้ายด้วย CSS

เพื่อให้อิลิเมนต์คงค่าสไตล์ที่ตั้งค่าไว้ใน keyframe สุดท้าย (หลังแอนิเมชันจบ) ให้ใช้คุณสมบัติ animation-fill-mode: forwards

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

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      width: 150px;
      height: 200px;
      position: relative;
      background: red;
      animation-name: myanim;
      animation-duration: 2s;
      animation-fill-mode: forwards;
    }
    @keyframes myanim {
      from { left: 0px; background-color: green; }
      to { left: 200px; background-color: blue; }
    }
  </style>
</head>
<body>
  <div></div>
</body>
</html>

คำอธิบาย: animation-fill-mode: forwards ทำให้หลังแอนิเมชันจบ อิลิเมนต์คงสไตล์ของ keyframe สุดท้าย (to { left: 200px; background-color: blue; }) ไม่กลับสู่สถานะเดิม (background: red) ต่างจาก backwards (คง keyframe แรก) และ both (คงทั้งสองข้าง)