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

วิธีนำแอนิเมชันพื้นฐานไปใช้ใน JavaScript


เพื่อนำแอนิเมชันพื้นฐานไปใช้ใน JavaScript ให้ใช้คุณสมบัติของ DOM object และ JavaScript รายการต่อไปนี้มีเมธอด DOM ที่แตกต่างกัน

  • เราใช้ฟังก์ชัน JavaScript getElementById() เพื่อดึง DOM object แล้วมอบให้กับตัวแปรทั่วไป imgObj
  • เรากำหนดฟังก์ชันเริ่มต้น init() เพื่อเริ่มต้น imgObj โดยตั้งค่า position และ left attributes
  • เราเรียกฟังก์ชันเริ่มต้นตอนโหลดหน้าต่าง
  • สุดท้ายเราเรียกฟังก์ชัน moveRight() เพื่อเพิ่มระยะทาง left ขึ้น 10 พิกเซล คุณสามารถตั้งค่าเป็นค่าลบเพื่อเลื่อนไปซ้ายได้เช่นกัน
<html> 
    <head> 
        <title>JavaScript Animation</title> 
        <script> 
            <!-- 
            var imgObj = null; 
            function init() { 
                imgObj = document.getElementById('myImage'); 
                imgObj.style.position= 'relative'; 
                imgObj.style.left = '0px'; 
            } 
            function moveRight() { 
                imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px'; 
            } 
            window.onload =init; 
            //--> 
        </script> 
    </head> 
    <body> 
        <form> 
            <img id="myImage" src="/images/html.gif" /> 
            <p>Click button below to move the image to right</p> 
            <input type="button" value="Click Me" onclick="moveRight();" /> 
        </form> 
    </body> 
</html>