今天看了網上的一個教學視頻,感覺還不錯,又把之前學的js基礎複習了一點(已經半學期沒碰了)。
下面附上代碼吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>鍵盤事件聯繫</title>
<style>
*{
padding: 0;
margin: 0;
}
html{
height: 100%;
}
body{
height: 100%;
background: url('images/bg.jpg');
background-size: 100% 100%;
}
#site{
position: relative;
height: 100%;
}
img{
position: absolute;
width: 200px;
height: 300px;
bottom: 50px;
}
</style>
</head>
<body>
<div id="site">
<img src="images/YAGAMI/stand.gif" id="MC">
</div>
</body>
<script type="text/javascript">
var imgObj=document.getElementById("MC");
var left=0;
var Game=new game(imgObj);
document.οnkeydοwn=key;
function key(e){
var e=e||window.event;
Game.keydown(e.keyCode);
this.οnkeyup=function(){
Game.keyup();
this.οnkeydοwn=key;
}
document.οnkeydοwn=null;
}
function game(obj){
this.left=0;
this.timer=null;
this.active={
"39":function(){
obj.src="images/YAGAMI/advance.gif";
this.timer=setInterval(function(){
this.left+=5;
obj.style.left=this.left + "px";
}.bind(this),1000/60);
//bind()方法低版本瀏覽器不支持。
},
"37":function(){
obj.src="images/YAGAMI/retreat.gif";
this.timer=setInterval(function(){
this.left-=5;
obj.style.left=this.left+"px";
}.bind(this),1000/60);
},
"40":function(){
obj.src="images/YAGAMI/7490881c38cfba5ef724e4ba.gif";
},
"stop":function(){
obj.src="images/YAGAMI/stand.gif";
}
};
}
game.prototype.keydown=function(keyCode){
for(var key in this.active){
if(key==keyCode){
this.active[key].call(this);
}
}
}
game.prototype.keyup=function(){
clearInterval(this.timer);
this.active.stop();
}
</script>
</html>
代碼中所用到的圖片有