坦克大战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
相关文章推荐
- LazyGame源码运行过程
- Hive架构及Hive On Spark
- 从头认识java-2.5 三元运算符和字符串操作符
- Notepad++配置C/C++,Python开发环境 4000
- Android Studio中配置及使用OpenCV示例(一)
- 打字母游戏
- 结构体嵌套中的内存对齐问题
- sc delete 服务器名提示“指定的服务已经标记为删除”
- 多线程学习之六生产消费者模式
- Spring原来属于这家公司
- VC++ CButton::SetCheck 的使用方法
- Tabris.js 介绍与学习<2>
- hdoj 1598 find the most comfortable road 【并查集+贪心】
- Maven内置隐式变量
- SSIS中的容器和数据流—简单介绍
- [leetcode]Remove Nth Node From End of List
- 转场动画 CATransition ,效果惊人
- jQuery判断当前元素显示状态并控制元素的显示与隐藏
- js url参数的获取和设置以及删除
- iOS界面编程-UITextField