用键盘的方向按钮控制小鸟的移动距离和方向

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用方向键盘控制小鸟的移动方向</title>
<style type="text/css">
img{position:absolute;width:150px;}
.right{transform: rotateY(180deg);}
</style>
<script type="text/javascript">
window.onload = function(){
var bird = document.getElementById('bird');
//绑定keydown事件

//通过转码绑定方向盘
document.onkeydown = function(e){
var startLest = parseInt(bird.style.left);
var startTop = parseInt(bird.style.top);
e = e || window.event;//兼容性问题
// if(e.keyCode==37){
// bird.style.left = startLest - 10 +'px';
// }else if(e.keyCode==39){
// bird.style.left = startLest + 10 +'px';
// }else if(e.keyCode==38){
// bird.style.top = startTop - 10 +'px';
// }else if(e.keyCode==40){
// bird.style.top = startTop + 10 +'px';
// }
switch(e.keyCode){
case 37:
//每次移动的距离和方向
bird.style.left = startLest - 10 +'px';
bird.className='';
break;
case 39:
bird.style.left = startLest + 10 +'px';
bird.className='right';
break;
case 38:
bird.style.top = startTop - 10 +'px';
break;
case 40:
bird.style.top = startTop + 10 +'px';
break;
}
}
}
</script>
</head>
<body>
<img src="images/bird.jpg" id='bird' style="top:0px;left:10px;">
</body>
</html>

posted @ 2016-04-22 10:02  零浪  阅读(333)  评论(0编辑  收藏  举报