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

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

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

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

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

คำอธิบาย: animation-fill-mode: backwards ทำให้ก่อนเริ่มแอนิเมชัน (ในช่วง animation-delay) อิลิเมนต์จะแสดงสไตล์ของ keyframe แรก (from { background-color: green; }) แทนที่จะเป็นสไตล์เดิม (background: red)