您的位置:首页 > 其它

坦克大战1.0

2015-10-23 16:10 375 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#background{
width: 500px;
height: 455px;
background-color: #999999;
margin: 0px auto;
position: relative;
}
#imgdiv{
width: 50px;
height: 45px;
background: url("tank.gif") 0px 0px no-repeat;
position: absolute;
}
</style>
</head>
<body>
<div id="background">
<div id="imgdiv"></div>
</div>
<script>
var body = document.getElementsByTagName("body")[0];
var imgdiv = document.getElementById("imgdiv");
var bacdiv = document.getElementById("background");
function Tank(x,y,speed){
this.x = x;
this.y = y;
this.speed = speed;
//this.direct = direct;
//初始化
imgdiv.style.top = this.y + "px";
imgdiv.style.left = this.x + "px";

this.move = function move(event){

switch(event.keyCode){
//左
case 37:
imgdiv.style.backgroundPosition="0px 0px";
//如果还没有碰到左边,继续移动
if(this.x > 0){
this.x -= this.speed;
}
break;
//上
case 38:
imgdiv.style.backgroundPosition="-50px 0px";
//首先判断是否到达顶部,到达顶部后不再向上移动
if(this.y > 0){
this.y -= this.speed;
}
break;
//右:
case 39:
//如果还没有碰到右边,继续移动
imgdiv.style.backgroundPosition="-150px 0px";
if(this.x + imgdiv.offsetWidth < bacdiv.offsetWidth){
this.x += this.speed;
}
break;
//下
case 40:
//如果还没有到达底部,继续移动
imgdiv.style.backgroundPosition="-100px 0px";
if(this.y + imgdiv.offsetHeight < bacdiv.offsetHeight){
this.y += this.speed;
}
break;
default:
window.alert("请按上下左右方向键控制");
}
imgdiv.style.top = this.y + "px";
imgdiv.style.left = this.x + "px";
}
}
body.onkeydown = function dosomething(event){
tank.move(event);
}
var tank = new Tank(200,0,10);
</script>
</body>
</html>


实现截图:



注意:

注意标点符号一定不要写错,; 和:容易混淆;

js中控制css,格式如:imgdiv.style.backgroundPosition=”0px 0px”;

background: url("tank.gif") 0px 0px no-repeat;


等同于:

background-position:0px 0px;
background-image: url("tank.gif");
background-repeat: no-repeat;


链接:

4. 键盘keyCode链接:/article/5890636.html

5. 通过背景位置来使用CSS精灵: http://book.2cto.com/201208/1734.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: