<!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鏈接:http://www.cnblogs.com/shyy/archive/2012/04/09/2453029.html
5. 通過背景位置來使用CSS精靈: http://book.2cto.com/201208/1734.html