ウェブ学のすすめ

Study of Web Design & Programing

DOMを使用したアニメーション

DOMを使用してアニメーションを作ってみました。CSS3を使っていないのでIEでもアニメーションが動きます。

デモ

HTML

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>アニメーション</title>
</head>
<body>
  	<h1><img src="http://jsrun.it/assets/p/e/N/a/peNaO.png" width="250"></h1>
	<form>
		<p>
			<input type="button" id="sBtn" value="スタート" onclick="startStop();">
		</p>
	</form>
	<div id="snake">
		<img src="http://jsrun.it/assets/w/G/Q/q/wGQq0.png" width="200">
	</div>
</body>
</html>

CSS

@charset "utf-8";
* {
    margin:0;
    padding:0;
}

body {
    background:url(http://jsrun.it/assets/b/b/D/m/bbDmu.png);
    
}
h1 {
    width:250px;
    margin:0 auto;
}

#snake {
    position: absolute; /* ブラウザ左上を基準 */
    top: 250px;
    left: 0;
}
#sBtn {
    margin:20px;
}

JavaScript

var INTERVAL = 10;  //アニメーションの間隔(msec)
var x =0;  //X座標
var animating = false;  //アニメーションを実行中かどうか
var timer;  //タイマーID
    

function move(){
  aSnake =  document.getElementById('snake');	
  x = x + 2;
  aSnake.style.left = x + 'px';
  if (x > 465) {
    x = -200;
  }
  timer = setTimeout('move()', INTERVAL);	
}

function startStop(){	
  if (animating) {
    clearTimeout(timer);
    document.getElementById('sBtn').value = 'スタート';
  } else {
    document.getElementById('sBtn').value = 'ストップ';
    move();
  }
  animating = !animating;
}