原理:找到4张图,关于坦克的上下左右
设置对应的上下左右的变量为false,当对应变量为true时(对应键盘的keyCode),使用setInterval改变对应图片的offset值,使其移动,当对应键盘keyup时对应变量为false
img{
position:absolute;
left:0;
top:0;
}
<img src="img/top.jpg" width="200" height="200"/>
var oImg=document.querySelectorAll('img')[0];
var aTop=false,aRight=false,aBottom=false, aLeft=false;
function myClient(){
return {
width:window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0,
height:window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0
}
}
setInterval(function(){
if(aLeft){
oImg.style.left=oImg.offsetLeft-6+"px";
}
if(aRight){
oImg.style.left=oImg.offsetLeft+6+"px";
}
if(aTop){
oImg.style.top=oImg.offsetTop-6+"px";
}
if(aBottom){
oImg.style.top=oImg.offsetTop+6+"px";
}
if(oImg.offsetTop>=myClient().height){
oImg.style.top=oImg.offsetTop-6+"px";
console.log(myClient().height)
}
if(oImg.offsetLeft>=myClient().width){
oImg.style.left=oImg.offsetLeft-6+"px";
console.log(myClient().height)
}
if(oImg.offsetLeft<=0){
oImg.style.left=0+"px";
}
if(oImg.offsetTop<=0){
oImg.style.top=0+"px";
}
},30);
document.onkeydown=function(ev){
var ev=ev||event;
switch(ev.keyCode){
case 37:aLeft=true; oImg.src='img/left.jpg'; break;
case 38:aTop=true; oImg.src='img/top.jpg'; break;
case 39:aRight=true; oImg.src='img/right.jpg'; break;
case 40:aBottom=true; oImg.src='img/bottom.jpg'; break;
}
}
document.onkeyup=function(ev){
var ev=ev||event;
switch(ev.keyCode){
case 37:aLeft=false; break;
case 38:aTop=false;break;
case 39:aRight=false; break;
case 40:aBottom=false;break;
}
}