html5获取键盘并设置触发事件,通过指定键添加事件
首先我们通过添加一个 弹出框获取键盘对应的编码,不同的电脑,编码是不一样的,例如宏碁和联想就不一样
//打印当前按下键的编号 alert(e.code);
然后整个按下事件及弹起事件:
function keyDown(e){ //打印当前按下键的编号 // 跳 if(g_hero.isdie==1)return; if(e.code=="ArrowUp"){ g_hero.jump=1; } //蹲下 if(e.code=="ArrowDown"){ g_hero.dun=1; //前进 } if(e.code=="ArrowLeft"){ g_hero.x-=2; //后退 } if(e.code=="ArrowRight"){ g_hero.x+=2; } //攻击 if(e.code=="KeyA"){ var x=g_hero.x+g_hero.img1.width; var y=g_hero.y; if(g_hero.dun==1){ y=g_hero.y+28; }else if(g_hero.jump==1){ y=g_hero.jumpy*1.3; } shot=new Bord(x,y,"bordimg"); shotArray.push(shot);
//添加音效 var Music=new Audio(); Music.src="../audio/SE_STAGE2_HIT_BUBBLE.ogg"; Music.play(); } }
键盘 弹起键触发事件 function keyUp(e){ //蹲下 if(e.code=="ArrowDown"){ g_hero.dun=0; //跳起 } if(e.code=="ArrowUp"){ g_hero.jump=0; g_hero.jumpy=g_hero.y; } //前进 if(e.code=="ArrowLeft"){ g_hero.go=0; //后退 } if(e.code=="ArrowRight"){ g_hero.back=0; } }
不为失败找原因,要为成功找方法!