键盘事件

  1. // document.onkeydown=function(){
  2. // console.log('keydown');
  3. // //不抬起按键会一直触发
  4. // }
  5. // document.onkeyup=function() {
  6. // console.log('keyup')
  7. // }
  8. // document.onkeypress=function() {
  9. // console.log('keypress');
  10. // }
  11. //keydown->keypress->keyup
  12. //所有按键都可以触发
  13. document.onkeydown=function(e){
  14. console.log(e);
  15. console.log(e.charCode)//0 无数字
  16. console.log(e.keyCode)//键盘顺位码
  17. //keyCode有上下左右
  18. }
  19. //只能触发字符类按键,上下左右不行
  20. document.onkeypress=function(e) {
  21. console.log(e);
  22. console.log(e.charCode)//1 有数字 ascii码
  23. console.log(e.keyCode);//一样 有
  24. var str=String.fromCharCode(e.charCode)
  25. console.log(str);
  26. //能得到大写的G、H、L,keyCode不行
  27. //只能触发字符类,别的不行,shift、上下左右
  28. //keyCode没有上下左右
  29. }

keyCode表

1.png2.png3.png

例子

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title></title>
  8. <style>
  9. .box {
  10. position: absolute;
  11. top: 0;
  12. left: 0;
  13. width: 100px;
  14. height: 100px;
  15. background-color: green;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div class="box"></div>
  21. <script src="./js/utils.js"></script>
  22. <script>
  23. var box = document.getElementsByClassName('box')[0];
  24. document.onkeydown = function (e) {
  25. var e = e || window.event,
  26. code = e.keyCode,
  27. bLeft = getStyles(box, 'left'),
  28. bTop = getStyles(box, 'top');
  29. switch (code) {
  30. case 37:
  31. box.style.left = bLeft - 5 + 'px';
  32. break;
  33. case 39:
  34. box.style.left = bLeft + 5 + 'px';
  35. break;
  36. case 38:
  37. box.style.top = bTop -5 + 'px';
  38. break;
  39. case 40:
  40. box.style.top = bTop + 5 + 'px';
  41. break;
  42. default:
  43. break;
  44. }
  45. }
  46. </script>
  47. </body>
  48. </html>

贪吃蛇

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. .wrap{
  10. position: relative;
  11. width: 500px;
  12. height: 500px;
  13. margin: 50px auto;
  14. background-color: #000;
  15. overflow: hidden;
  16. }
  17. .round{
  18. display: block;
  19. position: absolute;
  20. width: 20px;
  21. height: 20px;
  22. border-radius: 50%;
  23. background-color: green;
  24. z-index: 1;
  25. }
  26. .round.head{
  27. background-color: red;
  28. }
  29. .food{
  30. display: block;
  31. position: absolute;
  32. width: 20px;
  33. height: 20px;
  34. border-radius: 50%;
  35. background-color: yellow;
  36. z-index: 2;
  37. }
  38. </style>
  39. </head>
  40. <body>
  41. <div class="wrap"></div>
  42. <script src="./js/untils.js"></script>
  43. <script src="./js/index.js"></script>
  44. </body>
  45. </html>
  1. window.onload = function () {
  2. init();
  3. }
  4. function init() {
  5. initGame();
  6. }
  7. var initGame = (function () {
  8. var wrap = document.getElementsByClassName('wrap')[0],
  9. wrapW = getStyles(wrap, 'width'),
  10. wrapH = getStyles(wrap, 'height'),
  11. t = null;
  12. var Snake = function () {
  13. this.bodyArr = [{
  14. x: 0,
  15. y: 0
  16. },
  17. {
  18. x: 0,
  19. y: 20
  20. },
  21. {
  22. x: 0,
  23. y: 40
  24. },
  25. {
  26. x: 0,
  27. y: 60
  28. },
  29. {
  30. x: 0,
  31. y: 80
  32. },
  33. {
  34. x: 0,
  35. y: 100
  36. }
  37. ];
  38. this.dir = 'DOWN'
  39. }
  40. Snake.prototype = {
  41. init: function () {
  42. this.bindEvent();
  43. this.createFood();
  44. this.initSnake();
  45. this.run();
  46. },
  47. bindEvent: function () {
  48. var _self = this;
  49. addEvent(document, 'keydown', function () {
  50. _self.changeDir();
  51. });
  52. },
  53. initSnake: function () {
  54. var arr = this.bodyArr,
  55. len = arr.length,
  56. frag = document.createDocumentFragment(),
  57. item;
  58. for (var i = 0; i < len; i++) {
  59. item = arr[i];
  60. var round = document.createElement('i'); //i标签
  61. // console.log(round);
  62. // 此处i是循坏中的i 查找数组中最后一项
  63. round.className = i === len - 1 ? 'round head' : 'round';
  64. round.style.left = item.x + 'px';
  65. round.style.top = item.y + 'px';
  66. frag.appendChild(round);
  67. }
  68. wrap.appendChild(frag);
  69. },
  70. run: function () {
  71. var _self = this
  72. t = setInterval(function () {
  73. _self.move();
  74. }, 500);
  75. },
  76. move: function () {
  77. var arr = this.bodyArr,
  78. len = arr.length;
  79. for (var i = 0; i < len; i++) {
  80. if (i === len - 1) {
  81. this.setHeadXY(arr);
  82. } else {
  83. arr[i].x = arr[i + 1].x;
  84. arr[i].y = arr[i + 1].y;
  85. }
  86. }
  87. this.eatFood(arr);
  88. this.removeSnake();
  89. this.initSnake();
  90. this.headInBody(arr);
  91. },
  92. setHeadXY: function (arr) {
  93. var head = arr[arr.length - 1];
  94. switch (this.dir) {
  95. case 'LEFT':
  96. if (head.x <= 0) {
  97. head.x = wrapW - 20;
  98. } else {
  99. head.x -= 20;
  100. }
  101. break;
  102. case 'RIGHT':
  103. if (head.x >= wrapW - 20) {
  104. head.x = 0;
  105. } else {
  106. head.x += 20;
  107. }
  108. break;
  109. case 'UP':
  110. if (head.y <= 0) {
  111. head.y = wrapH - 20;
  112. } else {
  113. head.y -= 20;
  114. }
  115. break;
  116. case 'DOWN':
  117. if (head.y >= wrapH - 20) {
  118. head.y = 0;
  119. } else {
  120. head.y += 20;
  121. }
  122. break;
  123. default:
  124. break;
  125. }
  126. },
  127. headInBody: function (arr) {
  128. var headX = arr[arr.length - 1].x,
  129. headY = arr[arr.length - 1].y;
  130. for (var i = 0; i < arr.length - 2; i++) {
  131. item = arr[i];
  132. if (headX === item.x && headY === item.y) {
  133. var _self = this;
  134. setTimeout(function () {
  135. alert('游戏结束');
  136. clearInterval(t);
  137. _self.removeSnake();
  138. _self.removeFood();
  139. }, 100)
  140. }
  141. }
  142. },
  143. removeSnake: function () {
  144. var bodys = document.getElementsByClassName('round');
  145. while (bodys.length > 0) {
  146. bodys[0].remove();
  147. }
  148. },
  149. changeDir: function () {
  150. var e = e || window.event;
  151. code = e.keyCode;
  152. this.setDir(code);
  153. },
  154. setDir: function () {
  155. switch (code) {
  156. case 37:
  157. if (this.dir !== 'RIGHT' && this.dir !== 'LEFT') {
  158. this.dir = 'LEFT';
  159. }
  160. break;
  161. case 39:
  162. if (this.dir !== 'RIGHT' && this.dir !== 'LEFT') {
  163. this.dir = 'RIGHT';
  164. }
  165. break;
  166. case 38:
  167. if (this.dir !== 'UP' && this.dir !== 'DOWN') {
  168. this.dir = 'UP';
  169. }
  170. break;
  171. case 40:
  172. if (this.dir !== 'UP' && this.dir !== 'DOWN') {
  173. this.dir = 'DOWN';
  174. }
  175. break;
  176. default:
  177. break;
  178. }
  179. },
  180. createFood: function () {
  181. var food = document.createElement('i');
  182. food.className = 'food';
  183. food.style.left = this.setRandomPos(wrapW) * 20 + 'px';
  184. food.style.top = this.setRandomPos(wrapH) * 20 + 'px';
  185. wrap.appendChild(food);
  186. },
  187. setRandomPos: function (size) {
  188. return Math.floor(Math.random() * (size / 20))
  189. },
  190. eatFood: function (arr) {
  191. var food = document.getElementsByClassName('food')[0],
  192. foodX = getStyles(food, 'left'),
  193. foodY = getStyles(food, 'top'),
  194. headX = arr[arr.length - 1].x,
  195. headY = arr[arr.length - 1].y,
  196. x,
  197. y;
  198. if (headX === foodX && headY === foodY) {
  199. this.removeFood();
  200. this.createFood();
  201. if (arr[0].x == arr[1].x) {
  202. x = arr[0].x;
  203. if (arr[0].y > arr[1].y) {
  204. y = arr[0].y + 20;
  205. } else if (arr[0].y < arr[1].y) {
  206. y = arr[0].y - 20;
  207. }
  208. } else if (arr[0].y === arr[1].y) {
  209. y = arr[0].y;
  210. if (arr[0].x > arr[1].x) {
  211. x = arr[0].x + 20;
  212. } else if (arr[0].x < arr[1].x) {
  213. x = arr[0].x - 20;
  214. }
  215. }
  216. arr.unshift({
  217. x,
  218. y
  219. })
  220. }
  221. },
  222. removeFood: function () {
  223. var food = document.getElementsByClassName('food')[0];
  224. food.remove();
  225. }
  226. }
  227. return new Snake().init();
  228. });