Để triển khai animation cơ bản trong JavaScript, dùng thuộc tính đối tượng DOM và JavaScript. Danh sách các phương thức DOM:
- Dùng hàm getElementById() để lấy đối tượng DOM và gán cho biến toàn cục imgObj.
- Định nghĩa hàm khởi tạo init() để khởi tạo imgObj nơi thiết lập position và left.
- Gọi hàm khởi tạo khi tải trang (window load).
- Cuối cùng gọi moveRight() để tăng left 10px. Có thể đặt giá trị âm để di chuyển sang trái.
<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>Nhấn nút dưới để di chuyển ảnh sang phải</p> <input type="button" value="Click Me" onclick="moveRight();" /> </form> </body> </html>