<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> </body> <script> document.onkeydown = function(e){ var e = e || event; //alert(e.keyCode); //alert(e.shiftKey); if(e.shiftKey){ if (e.keyCode == 65) { alert('我按了一下A键') } } console.log('我按下了键盘') } document.onkeyup = function(){ console.log('我松开了键盘') } document.onkeypress = function(){ console.log('按了一次键盘') } </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{margin:0px;padding:0px;} #box{width:100px;height:100px;position:absolute;/*background:pink;*/} #parent{width:400px;height:400px;border:1px solid red;background-image:url(./bg.jpg);} </style> </head> <body> <div id="parent"> <div id="box" style="left:0px;top:0px;"> <img src="./me.png" alt=""> </div> </div> </body> <script> var box = document.getElementById('box'); //上键 38 //下键 40 //左键 37 //右键 39 document.onkeydown = function(e){ var e = e || event; //alert(e.keyCode); switch(e.keyCode){ case 37: if((parseInt(box.style.left)-10)>0){ //alert('按了左键') box.style.left = parseInt(box.style.left)-10+'px'; }else{ box.style.left = '0px'; } break; case 38: if((parseInt(box.style.top)-10)>0){ //alert('按了上键') box.style.top = parseInt(box.style.top)-10+"px"; }else{ box.style.top="0px"; } break; case 39: //alert('按了右键') if(parseInt(box.style.left)< 300){ box.style.left = parseInt(box.style.left) + 10 + 'px'; }else{ box.style.left= 300+'px'; } break; case 40: //alert('按了下键') if(parseInt(box.style.top) < 300){ box.style.top = parseInt(box.style.top) + 10 +'px'; }else{ box.style.top='300px'; } break; } } </script> </html>
点击 "运行实例" 按钮查看在线实例
点击 "运行实例" 按钮查看在线实例