AnimationEvent ใน HTML DOM
AnimationEvent เป็นออบเจ็กต์ใน JavaScript ที่จัดการเหตุการณ์ (events) ที่เกิดขึ้นเมื่อ CSS animation ทำงาน ให้ข้อมูลเกี่ยวกับเหตุการณ์ที่เกี่ยวข้องกับ animation ให้การควบคุม CSS animations ได้มากขึ้น แสดงความสัมพันธ์ระหว่าง events และ animation โดยอธิบายว่า event ใดเป็นตัวกระตุ้นการทำ animation
คุณสมบัติ (Properties)
| คุณสมบัติ | คำอธิบาย |
|---|---|
animationName | คืนชื่อของ animation ที่กำลังทำงาน (จาก animation-name) |
elapsedTime | คืนเวลาที่ผ่านไปตั้งแต่ animation เริ่มทำงาน (วินาที) ไม่นับเวลาที่ pause |
pseudoElement | คืนชื่อ pseudo-element ของ animation (เช่น ::before, ::after, ::first-line) |
ไวยากรณ์ (Syntax)
animationEvent.property
ตัวอย่างการใช้งาน
ตัวอย่างด้านล่างแสดงการจับ event animationstart และอ่านค่า animationName
<!DOCTYPE html>
<html>
<head>
<style>
#ANIM-DIV {
margin: 10px;
width: 400px;
height: 100px;
background: lightgreen;
position: relative;
font-size: 30px;
animation-name: animMove;
animation-duration: 5s;
}
@-webkit-keyframes animMove {
from { top: 0px; }
to { top: 200px; }
}
</style>
</head>
<body>
<div id="ANIM-DIV"></div>
<script>
var x = document.getElementById("ANIM-DIV");
x.addEventListener("animationstart", myAnimFunction);
function myAnimFunction(event) {
this.innerHTML = "The animation-name is: " + event.animationName;
}
</script>
</body>
</html>
หมายเหตุ: ทดสอบบน Chrome 74.0.3729.169 โปรดตรวจสอบความเข้ากันได้ของเบราว์เซอร์สำหรับ animationEvent
ผลลัพธ์
เริ่มต้น: กล่องสีเขียวอ่อนขนาด 400x100px อยู่ตำแหน่งเดิม
เมื่อ animation เริ่ม: แสดงข้อความ "The animation-name is: animMove" ภายในกล่อง
หลัง 5 วินาที: กล่องเลื่อนลง 200px
คำอธิบายโค้ด
- CSS Animation: กำหนด
animation-name: animMoveและanimation-duration: 5s - Keyframes:
@keyframes animMoveกำหนดการเคลื่อนที่จาก top:0 ถึง top:200px - Event Listener:
addEventListener("animationstart", ...)จับเหตุการณ์เริ่มต้น - Event Object: รับผ่านพารามิเตอร์
eventเข้าถึงevent.animationName
เหตุการณ์ Animation อื่นๆ
animationstart- เริ่มต้น animationanimationend- จบ animationanimationiteration- จบรอบหนึ่ง (เมื่อanimation-iteration-count> 1)animationcancel- animation ถูกยกเลิก (ไม่รองรับทุกเบราว์เซอร์)