事件基础(二)键盘的事件

  onclick=onmouseup+onmousedown

  onkeypress=onkeydown+onkeyup

  keyCod(键值,键盘上每个键都对应一个唯一的值)

offset

offsetWidth,offsetLeft,offsetHeight ……代表的是实际的值

获取键盘的值需要用到事件对象event,火狐下用ev

键盘控制div的移动

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#div1 {100px; height:100px; background:#CCC; position:absolute;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
document.onkeydown=function (ev)
{
    var oEvent=ev||event;
    var oDiv=document.getElementById('div1');
    
    //←        37
    //右        39
    
    if(oEvent.keyCode==37)
    {
        oDiv.style.left=oDiv.offsetLeft-10+'px';
    }
    else if(oEvent.keyCode==39)
    {
        oDiv.style.left=oDiv.offsetLeft+10+'px';
    }
};
</script>
</head>

<body>
<div id="div1"></div>
</body>
</html>
 Question:比如在做一个坦克大战的游戏中,按下方向键以后,坦克应该持续移动,而不是先移动一下,然后停顿一下,然后再继续移动。如何解决这个小问题?
 
键盘事件的获取:Ctrl+Enter留言
其实键盘事件 的函数和鼠标的事件是一致的,函数内容完全相同。
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>无标题文档</title>
 6 <script>
 7 window.onload=function ()
 8 {
 9     var oBtn=document.getElementById('btn1');
10     var oTxt1=document.getElementById('txt1');
11     var oTxt2=document.getElementById('txt2');
12     
13     oBtn.onclick=function ()
14     {
15         oTxt1.value+=oTxt2.value+'
';
16         oTxt2.value='';
17     };
18     
19     oTxt2.onkeydown=function (ev) //记住:是在文本框的基础上加的事件
20     {
21         var oEvent=ev||event;
22         
23         if(oEvent.ctrlKey && oEvent.keyCode==13)
24         {
25             oTxt1.value+=oTxt2.value+'
';
26             oTxt2.value='';
27         }
28     };
29 };
30 </script>
31 </head>
32 
33 <body>
34 <textarea id="txt1" rows="10" cols="40"></textarea><br />
35 <input id="txt2" type="text" />
36 <input id="btn1" type="button" value="留言" />
37 </body>
38 </html>
 
原文地址:https://www.cnblogs.com/xs-yqz/p/4433134.html