Manual Animation (Hoạt ảnh thủ công)
Người dùng kích hoạt từng bước (click nút).
- Dùng
getElementById()lấy DOM element. - Hàm
init()khởi tạo vị trí. - Gọi
moveRight()tăngleft10px mỗi lần click.
Ví dụ
<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 nút để di chuyển ảnh</p>
<input type="button" value="Click Me" onclick="moveRight();" />
</form>
</body>
</html>
Automated Animation (Hoạt ảnh tự động)
Dùng setTimeout() hoặc setInterval() để lặp tự động.
moveRight()gọisetTimeout(moveRight, 20)để lặp.- Hàm
stop()dùngclearTimeout()dừng lại và reset vị trí.
Ví dụ
<html>
<head>
<title>JavaScript Animation</title>
<script>
var imgObj = null, animate;
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';
animate = setTimeout(moveRight, 20);
}
function stop() {
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload = init;
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Điều khiển animation</p>
<input type="button" value="Start" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
</form>
</body>
</html>