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

AnimationEvent ใน HTML DOM

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

คำอธิบายโค้ด

  1. CSS Animation: กำหนด animation-name: animMove และ animation-duration: 5s
  2. Keyframes: @keyframes animMove กำหนดการเคลื่อนที่จาก top:0 ถึง top:200px
  3. Event Listener: addEventListener("animationstart", ...) จับเหตุการณ์เริ่มต้น
  4. Event Object: รับผ่านพารามิเตอร์ event เข้าถึง event.animationName

เหตุการณ์ Animation อื่นๆ

  • animationstart - เริ่มต้น animation
  • animationend - จบ animation
  • animationiteration - จบรอบหนึ่ง (เมื่อ animation-iteration-count > 1)
  • animationcancel - animation ถูกยกเลิก (ไม่รองรับทุกเบราว์เซอร์)