JS keyboard events (very detailed)

In JavaScript, when the user operates the keyboard, keyboard events are triggered. Keyboard events mainly include the following 3 types:

  • keydown: Triggered when a key is pressed on the keyboard. If you press and hold a key, the event will be triggered continuously, but the Opera browser does not support this continuous operation. When the event handler returns false, the default action will be canceled (such as keyboard characters entered, and keypress event response is also prohibited under IE and Safari browsers).
  • keypress: Triggered when a keyboard key is pressed and released. If you hold down a key, the event will be triggered continuously. When the event handler returns false, the default action (such as input keyboard characters) will be cancelled.
  • keyup: Triggered when a keyboard key is released. This event is only triggered once when the keyboard is released, not a continuous response state.

When the user is pressing to build a code, you can use the keydown, keypress and keyup events to get this information. Among them, keydown and keypress events are basically synonymous events, and their performance is exactly the same, but some browsers do not allow keypress events to obtain key press information. All elements support keyboard events, but keyboard events are mostly used in form input.

Example

The following example captures various details of the keyboard operation in real time, that is, the type of keyboard response time and the corresponding key value.

<textarea id="key"></textarea>
<script>
    var key=document.getElementById("key");
    key.onkeydown = f; //注册keydown事件处理函数
    key.onkeyup = f; //注册keyup事件处理函数
    key.onkeypress = f; //注册keypress事件处理函数
    function f (e) {
        var e = e || window.event; //标准化事件处理
        var s = e.type + " " + e.keyCode; //获取键盘事件类型和按下的值
        key.value = s;
    }
</script>

Keyboard event properties

The keyboard defines many attributes, as shown in the following table. Use these attributes to precisely control keyboard operations. Keyboard event attributes generally exist in the event object only when keyboard-related events occur, except for the ctrlKey and shiftKey attributes, because they can exist in water conservation events. For example, when pressing the Ctrl or Shift key, click the mouse operation.

Properties defined by keyboard events:

Attributes Description
keyCode This attribute contains the key value of the corresponding key in the keyboard
charCode This attribute contains the Unicode encoding of the corresponding key in the keyboard, only supported by DOM
target The node (including the element) where the event occurred, only supported by DOM
srcElement The element where the event occurred, only supported by IE
shiftKey Whether to press the Shift key, return true if pressed, otherwise false
ctrlKey Whether to press the Ctrl key, return true if pressed, otherwise false
altKey Whether to press the Alt key, if pressed, return true, otherwise false
metaKey Whether to press the Meta key, if it is pressed, it returns true, otherwise it is false, only DOM supports

Example 1

The ctrlKey and shiftKey attributes can exist in keyboard and mouse events, indicating whether the Ctrl and Shift keys on the keyboard are held down. The following example can detect whether the Ctrl and Shift keys are simultaneously pressed. If you press it at the same time and the mouse clicks on a page element, the element will be deleted from the page.

document.onclick = function (e) {
    var e = e || window.event; //标准化事件对象
    var t = e.target || e.srcElement; //获取发生事件的元素,兼容IE和DOM
    if (e.ctrlKey && e.shiftKey) { //如果同时按下Ctrl和Shift键
        t.parentNode.removeChild(t); //移除当前元素
    }
}

The keyCode and charCode attributes are more complicated to use, but they are more commonly used in actual development, so it is necessary to compare the performance of these two attributes in different event types and different browsers, as shown in the following table. Reading can select event response types and reference attribute values ​​in a targeted manner according to needs.

keyCode and charCode attribute values

Attributes IE event model DOM event model
keyCode(keypress) Returns the correct value of all character keys, distinguishing between uppercase (65-90) and lowercase (97-122) Function keys return the correct value, but Shift, Ctrl, Alt, PrintScreen, ScrollLock have no return value, and all other key values ​​return 0
keyCode(keydown) Return all key values ​​(except the PrintScreen key), the letter keys are all capitalized to display the key value (65~90) Return all key values ​​(except the PrintScreen key), the letter keys are all capitalized to display the key value (65~90)
keyCode(keyup) Return all key values ​​(except the PrintScreen key), the letter keys are all capitalized to display the key value (65~90) Return all key values ​​(except the PrintScreen key), the letter keys are all capitalized to display the key value (65~90)
charCode(keypress) The attribute is not supported Return character key, distinguish between uppercase state (65~90) and lowercase state (97~122), Shift, Ctrl, Alt, PrintScreen, ScrollLock have no return value, all other key values ​​return 0
charCode(keydown) The attribute is not supported All keys are 0
charCode(keyup) The attribute is not supported All keys are 0

The availability of some keys is not very correct, such as PageUp and Home keys. However, the commonly used function keys and character keys are relatively stable, as shown in the following table.

Key position and code value comparison table

Key position Code value Key position Code value
0~9 (number keys) 48~57 A~Z (letter keys) 65~90
Backspace (backspace key) 8 Tab (tab key) 9
Enter (Enter) 13 Space 32
Left arrow 37 Top arrow (up arrow key) 38
Rigth arrow (right arrow key) 39 Down arrow  40

Example 2

The following example demonstrates how to use the arrow keys to control the movement effect of page elements.

<div id="box"></div>
<script>
    var box = document.getElementById("box"); //获取页面元素的引用指针
    box.style.position = "absolute"; //色块绝对定位
    box.style.width = "20px"; //色块宽度
    box.style.height = "20px"; //色块高度
    box.style.backgroundColor = "red"; //色块背景
    document.onkeydown = keyDown;
    //在Document对象中注册keyDown事件处理函数
    function keyDown(event) { //方向键控制元素移动函数
        var event = event || window.event; //标准化事件对象
        switch (event.keyCode) { //获取当前按下键盘键的编码
            case 37:  //按下左箭头键,向左移动5个像素
                box.style.left = box.offsetLeft - 5 + "px";
                break;
            case 39: //按下右箭头键,向右移动5个像素
                box.style.left = box.offsetLeft + 5 + "px";
                break;
            case 38: //按下上箭头键,向上移动5个像素
                box.style.top = box.offsetTop - 5 + "px";
                break;
            case 40: //按下下箭头键,向下移动5个像素
                box.style.top = box.offsetTop + 5 + "px";
                break;
        }
        return false
    }
</script>

In the above example, first obtain the page elements, and control the absolute positioning, size and background color of the elements through CSS scripts. Then register the mouse down event type handler on the document object, detect the currently pressed arrow key in the event callback function keyDown(), and determine the position of the positioned element in the window. The offsetLeft and offsetTop attributes of the element can access its position in the page.

Keyboard response sequence

When the keyboard is pressed, multiple events will be triggered continuously, and they will occur in the following order.

For character keys, the response sequence of keyboard events: keydown -> keypress -> keyup.

For non-character keys (such as function keys or special keys), the corresponding sequence of keyboard events: keydown -> keyup.

If you press and hold a character key, the keydown and keypress events will continue to occur one by one until the key is released.

If a non-character key is pressed and held, only the keydown event will continue to occur until the key is released.

Example

Let's design a simple example to get the corresponding sequence of keyboard events.

<textarea id="text" cols="26" rows="16"></textarea>
<script>
    var n = 1; //定义编号变量
    var text = document.getElementById("text"); //获取文本区域的引用指针
    text.onkeydown = f;// 注册keydown事件处理函数
    text.onkeyup = f; //注册keyup事件处理函数
    text.onkeypress = f; //注册keypress事件处理函数
    function f(e) { //事件调用函数
        var e = e || window.event; //标准化事件对象
        text.value += (n++) + "=" + e.type +" (keyCode=" + e.keyCode + ")\n";
        //捕获事件响应信息
    }
</script>

The demonstration effect is as follows:

When inputting A, B, C:

When the Shift, Ctrl, and Alt function keys are input respectively:

When the character A is pressed continuously:

When the Shift key is continuously pressed:

 

Guess you like

Origin blog.csdn.net/zhangge3663/article/details/108335834