คุณสมบัติ animationFillMode ใช้ระบุวิธีการนำสไตล์ไปใช้ภายนอกช่วงเวลาการทำงานของอนิเมชัน เช่น หลังจากที่อนิเมชันสิ้นสุดลง หรือเมื่อมีการกำหนดหน่วงเวลา (delay) ไว้ คุณสมบัตินี้ช่วยให้สามารถตั้งค่าสไตล์ CSS ให้กับองค์ประกอบก่อนที่อนิเมชันจะเริ่มต้น และหลังจากที่สิ้นสุดแล้ว
ไวยากรณ์ (Syntax)
รูปแบบการตั้งค่าคุณสมบัติ animationFillMode ดังนี้:
object.style.animationFillMode = "none|forwards|backwards|both|initial|inherit"
ค่าที่ใช้ได้ (Values)
ค่าต่างๆ ที่สามารถกำหนดได้มีดังนี้:
| ค่า | คำอธิบาย |
|---|---|
| none | ค่าเริ่มต้น อนิเมชันจะไม่ได้นำสไตล์ใดๆ ไปใช้กับองค์ประกอบเป้าหมาย ไม่ว่าจะก่อนเริ่มต้นหรือหลังจบการทำงาน |
| forwards | นำสไตล์ของ keyframe สุดท้ายไปใช้กับองค์ประกอบเป้าหมายหลังจากอนิเมชันสิ้นสุด |
| backwards | นำสไตล์ของ keyframe แรกไปใช้กับองค์ประกอบเป้าหมายในช่วงหน่วงเวลา (delay) ก่อนที่อนิเมชันจะเริ่ม |
| both | นำกฎของ forwards และ backwards ไปใช้ทั้งคู่ |
| initial | ตั้งค่าคุณสมบัติให้เป็นค่าเริ่มต้น |
| inherit | สืบทอดคุณสมบัตินี้จากองค์ประกอบพาเรนต์ |
ตัวอย่าง (Example)
ตัวอย่างการใช้งานคุณสมบัติ animationFillMode:
<!DOCTYPE html> <html> <head> <style>
div {
height: 30px;
width: 30px;
background-color: orange;
animation: small 4s;
animation-fill-mode: forwards;
}
@keyframes small {
0% { width: 200px; height: 200px; background-color: white; }
33% { background-color: green; }
66% { background-color: violet; }
100% { background-color: darkred; }
}
</style>
<script>
function changeFillMode(){
document.getElementById("DIV1").style.animationFillMode="backwards";
document.getElementById("Sample").innerHTML="The animation fillmode is now backwards";
}
</script> </head>
<body>
<div id="DIV1"></div>
<p>Click the below button to change the above animation fillmode property</p>
<button onclick="changeFillMode()">CHANGE FILL</button>
<p id="Sample"></p>
</body> </html>
ผลลัพธ์ (Output)
ผลลัพธ์ที่ได้จะเป็นดังนี้:

เมื่ออนิเมชันสิ้นสุด สีของสี่เหลี่ยมจะเป็นสี dark red เนื่องจากเป็น keyframe สุดท้าย:

เมื่อคลิกปุ่ม CHANGE FILL สีจะเปลี่ยนเป็นสีส้ม ซึ่งเป็น keyframe แรก:

หมายเหตุ: คุณสมบัตินี้ไม่รองรับในเบราว์เซอร์ IE/Edge และ Safari