键值监听
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>onkeydown</title> </head> <body> <div id="div" style="100px;height: 100px;background: blue;position:absolute;top:0;left:0;"></div> </body> <script type="text/javascript"> var oDiv = document.getElementById('div'); var timer = null ; var iCode = {}; document.onkeydown = function(ev){ var ev = ev || window.event ; iCode[ev.keyCode]= true;//获取键值。 console.log(iCode);//利用JSON存储 } document.onkeyup = function(ev){ var ev = ev || window.event ; iCode[ev.keyCode] = false ; } timer = setInterval(function(){ if(iCode[37]){//左键 oDiv.style.left = oDiv.offsetLeft - 10 + 'px'; }if(iCode[38]){ //上键 oDiv.style.top = oDiv.offsetTop - 10 + 'px'; }if(iCode[39]){//右键 oDiv.style.left = oDiv.offsetLeft + 10 + 'px'; }if(iCode[40]){ //下键 oDiv.style.top = oDiv.offsetTop+ 10 + 'px'; } },20); </script> </html>