夺命雷公狗---javascript NO:12 事件对象2通过event事件对象实现box层的左右移动
实战盒子移动,目的为了做贪吃蛇
代码如下:
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> <style type=’text/css’> div#box{ width:100px; height:100px; position:absolute; border:1px solid red; } </style> <script src=’public.js’></script> <script> window.onload = function(){ var x = 50; //定义box层的横坐标 var y = 50; //定义box层的纵坐标 $(‘box’).style.left = x+’px'; $(‘box’).style.top = y+’px'; //onkeydown事件会在用户按下一个键盘按键时发生 document.onkeydown = function(event){ var code;//用于接收键盘键值 if(window.event){ //IE浏览器 code = window.event.keyCode; }else{ code = event.keyCode; } switch(code){ case 37: x–; break; case 38: y–; break; case 39: x++; break; case 40: y++; break; } $(‘box’).style.left = x+’px'; $(‘box’).style.top = y+’px'; } } </script> </head> <body> <div id=’box’></div> </body> </html>