Home > Web Front-end > JS Tutorial > A brief discussion on comprehensive control of js keyboard events

A brief discussion on comprehensive control of js keyboard events

黄舟
Release: 2016-12-13 09:32:57
Original
1219 people have browsed it

Mainly divided into four parts

Part One: Browser Key Events
Part Two: Compatible Browsers
Part Three: Code Implementation and Optimization
Part Four: Summary

Part One: Browser Key Events

To implement keylogging with js, you should pay attention to the three key event types of the browser, namely keydown, keypress and keyup, which correspond to onkeydown, keypress and keyup respectively. The three event handles onkeypress and onkeyup. A typical keypress will generate all three events, in order keydown, keypress, and then keyup when the key is released.

Among these three event types, keydown and keyup are relatively low-level, while keypress is relatively advanced. The so-called advanced here means that when the user presses shift + 1, keypress parses the key event and returns a printable "!" character, while keydown and keyup only record the shift + 1 event. [1]

But keypress is only effective for some characters that can be printed, and for function keys, such as F1-F12, Backspace, Enter, Escape, PageUP, PageDown and arrow direction will not generate keypress events, but keydown and keyup events can be generated. However, in FireFox, function keys can generate keypress events.

The event objects passed to keydown, keypress and keyup event handlers have some common properties. If Alt, Ctrl, or Shift are pressed together with a key, this is represented by the event's altKey, ctrlKey, and shiftKey properties, which are common to FireFox and IE.

Part 2: Browser Compatibility

Any js that involves browsers must consider browser compatibility issues.

Currently, the commonly used browsers are mainly based on IE and based on Mozilla. Maxthon is based on the IE kernel, while FireFox and Opera are based on the Mozilla kernel.

2.1 Initialization of the event

The first thing you need to know is how to initialize the event. The basic statement is as follows:

 function keyDown(){}
   document.onkeydown = keyDown;
Copy after login

When the browser reads this statement, no matter which key on the keyboard is pressed, the KeyDown() function will be called .

2.2 How to implement FireFox and Opera

FireFox and Opera are more troublesome to implement than IE, so I will describe them here first.

keyDown() function has a hidden variable - generally, we use the letter "e" to represent this variable.

  function keyDown(e)

The variable e represents a keystroke event. To find which key was pressed, use the which attribute:

e.which

e.which will give the index value of the key. The method of converting the index value into the alphanumeric value of the key requires the use of the static function String.fromCharCode(), as follows:

  String.fromCharCode(e.which)

Putting the above statements together, we can get which key was pressed in FireFox:

function keyDown(e) 
{          
var keycode = e.which;         
var realkey = String.fromCharCode(e.which);         
alert("按键码: " + keycode + " 字符: " + realkey);      
}     
document.onkeydown = keyDown;
Copy after login

2.4 Determine the browser type

The above learned how to obtain key events in various browsers Object method, then you need to determine the browser type below. There are many methods, some are easier to understand, and some are very clever. Let’s talk about the general method first: using the appName attribute of the navigator object. Of course, you can also use the userAgent attribute. Here Use appName to determine browser type, IE and Maxthon's appName is "Microsoft Internet Explorer" , and the appName of FireFox and Opera is "Netscape", so a code with a relatively simple function is as follows:

function keyUp(e) 
{           
if(navigator.appName == "Microsoft Internet Explorer")         
{            
var keycode = event.keyCode;             
var realkey = String.fromCharCode(event.keyCode);           
}else         
{              
var keycode = e.which;              
var realkey = String.fromCharCode(e.which);          
}         
alert("按键码: " + keycode + " 字符: " + realkey);      
}      
document.onkeyup = keyUp;
Copy after login

The simpler method is [2]:

 function keyUp(e) 
 {         
 var currKey=0,e=e||event;         
 currKey=e.keyCode||e.which||e.charCode;        
 var keyName = String.fromCharCode(currKey);         
 alert("按键码: " + currKey + " 字符: " + keyName);       
 }       
 document.onkeyup = keyUp;
Copy after login

The above method is more clever, briefly explain:

First of all, the code e=e||event; is for compatibility with browser event object acquisition. The meaning of this code in js is that if the hidden variable e exists in FireFox or Opera, then e||event returns e. If the hidden variable e does not exist in IE, then event is returned.

Secondly, currKey=e.keyCode||e.which||e.charCode; This sentence is to be compatible with the key code attribute of the browser key event object (see Part 3 for details). For example, in IE, there is only the keyCode attribute. There are which and charCode attributes in FireFox, and keyCode and which attributes in Opera.

The above code is only compatible with the browser, obtains the keyup event object, and simply pops up the key code and key characters, but a problem arises. When you press a key, the character keys are all in uppercase, and when you press the shift key, The characters displayed are very strange, so the code needs to be optimized.

Part 3: Code Implementation and Optimization

3.1 Key code and character code for key events

In IE, there is only one keyCode attribute, and its interpretation depends on the event type. For keydown, keyCode stores the key code. For For keypress events, keyCode stores a character code. There are no which and charCode attributes in IE, so the which and charCode attributes are always undefined.

The keyCode in FireFox is always 0. When the time is keydown/keyup, charCode=0, which is the key code. When the event keypress occurs, the values ​​of which and charCode are the same, and the character code is stored.

In Opera, the values ​​of keyCode and which are always the same. In the keydown/keyup event, they store the key code. In the keypress time, they store the character code, and charCode is not defined and is always undefined.

3.2 用keydown/keyup还是keypress

第一部分已经介绍了keydown/keyup和keypress的区别,有一条比较通用的规则,keydown事件对于功能按键来说是最有用的,而keypress事件对于可打印按键来说是最有用的[3]。

键盘记录主要是针对于可打印字符和部分功能按键,所以keypress是首选,然而正如第一部分提到的,IE中keypress不支持功能按键,所以应该用keydown/keyup事件来进行补充。

3.3 代码的实现

总体思路,用keypress事件对象获取按键字符,用keydown事件获取功能字符,如Enter,Backspace等。

代码实现如下所示

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML> 
<HEAD><TITLE>js 按键记录</TITLE> 
<META NAME="Generator" CONTENT="EditPlus"> 
<META NAME="Author" CONTENT="羽殇仁"> 
<META NAME="Keywords" CONTENT="js 按键记录"> 
<META NAME="Description" CONTENT="js 按键记录"> 
</HEAD> 
<BODY> 
<script type="text/javascript"> 
var keystring = "";//记录按键的字符串 function $(s){return document.getElementByIdx_x(s)?document.getElementByIdx_x(s):s;} 
function keypress(e) 
{   
var currKey=0,CapsLock=0,e=e||event;    
currKey=e.keyCode||e.which||e.charCode;   
CapsLock=currKey>=65&&currKey<=90;   
switch(currKey)   
{       
//屏蔽了退格、制表、回车、空格、方向键、删除键      
case 8: case 9:case 13:case 32:case 37:case 38:case 39:case 40:case 46:keyName = "";break;       
default:keyName = String.fromCharCode(currKey); break;   
}   
keystring += keyName; 
} 
function keydown(e) 
{   
var e=e||event;   
var currKey=e.keyCode||e.which||e.charCode;   
if((currKey>7&&currKey<14)||(currKey>31&&currKey<47))   
{      
switch(currKey)       
{         
case 8: keyName = "[退格]"; break;         
case 9: keyName = "[制表]"; break;         
case 13:keyName = "[回车]"; break;         
case 32:keyName = "[空格]"; break;         
case 33:keyName = "[PageUp]";  break;         
case 34:keyName = "[PageDown]";  break;         
case 35:keyName = "[End]";  break;         
case 36:keyName = "[Home]";  break;         
case 37:keyName = "[方向键左]";  break;         
case 38:keyName = "[方向键上]";  break;         
case 39:keyName = "[方向键右]";  break;         
case 40:keyName = "[方向键下]";  break;         
case 46:keyName = "[删除]";  break;         
default:keyName = "";  break;      
}      keystring += keyName;  
 }   
 $("content").innerHTML=keystring; 
 } 
 function keyup(e) 
 {   
 $("content").innerHTML=keystring; 
 } 
 document.onkeypress=keypress; 
 document.onkeydown =keydown; 
 document.onkeyup =keyup; 
 </script> 
 <input type="text" /> 
 <input type="button" value="清空记录" onclick="$(&#39;content&#39;).innerHTML = &#39;&#39;;keystring = &#39;&#39;;"/> 
 <br/>请按下任意键查看键盘响应键值:<span id="content"></span> 
 </BODY> 
 </HTML>
Copy after login

代码分析:

$():根据ID获取dom

keypress(e):实现对字符码的截获,由于功能按键要用keydown获取,所以在keypress中屏蔽了这些功能按键。

keydown(e):主要是实现了对功能按键的获取。

keyup(e):展示截获的字符串。

代码基本上就算实现完成了!呵呵

第四部分:总结

编写代码的最初目的是能够通过js记录按键,并返回一个字符串。

上述代码只是用js实现了基本的英文按键记录,对于汉字是无能为力,记录汉字,我能想到的办法,当然是用js,是用keydown和keyup记录底层按键事件,汉字解析当然无能为力。当然你可以用DOM的方式直接获取input中的汉字,但这已经离开了本文讨论的用按键事件实现按键记录的本意。

上述代码还可以实现添加剪切板的功能,监控删除的功能等等。。。

这篇浅谈js键盘事件全面控制就是小编分享给大家的全部内容了,希望能给大家一个参考,

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template