坦克移动

原理:找到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;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值