<head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title>推箱子</title> <meta name="keywords" content="关键字列表" /> <meta name="description" content="网页描述" /> <link rel="stylesheet" type="text/css" href="" /> <style> #gg{ width:50px; height:50px; background:red; left:0; top:0; position:absolute; } </style> <script> //封装一个函数获取指定id的DOM对象 function $(id){ //返回一个获取的对象 return document.getElementById(id); } //定义变量 var x=0,y=0; window.onload=function(){ //功能键按下触发事件 document.onkeydown=function(event){ var cold; //判断兼容性并保存值 if(window.event){ code=window.event.keyCode; }else{ cold=event.keyCode; } //判断是什么键 switch(cold){ case 37: x-=5; break; case 38: y-=5; break; case 39: x+=5; break; case 40: y+=5; break; } //保存值 $(‘gg‘).style.left=x+‘px‘; $(‘gg‘).style.top=y+‘px‘; } } </script> </head> <body> <div id=‘gg‘></div> </body> </html>
时间: 2024-10-12 12:31:25