KeyboardEvent
Baseline
Widely available
*
This feature is well established and works across many devices and browser versions. It’s been available across browsers since julio de 2015.
* Some parts of this feature may have varying levels of support.
Los objetos KeyboardEvent describen una interacción del usuario con el teclado. Cada evento describe una tecla; el tipo de evento(keydown, keypress, o keyup) identifica el tipo de acción realizada.
Nota:
El KeyboardEvent solo indica qué está pasando en una tecla. Cuando necesite manejar la entrada de texto, use el evento input de HTML5 en su lugar. Por ejemplo, si el usuario introduce texto desde un sistema de tipo manuscrito como una tableta, los eventos para teclas no podrán ser lanzados.
Constructor
KeyboardEvent()-
Crea un objeto
KeyboardEvent.
Métodos
Esta interfaz también hereda métodos de sus padres, UIEvent and Event.
KeyboardEvent.getModifierState()-
Devuelve un
Booleanindicando si una tecla modificadora, como Alt, Shift, Ctrl, Meta, fue pulsada cuando el evento fue creado. KeyboardEvent.initKeyEvent()Obsoleto-
Inicializa un objeto
KeyboardEvent. Este método solo ha sido implementado por Gecko (otros usadosKeyboardEvent.initKeyboardEvent()) y nunca más será usado. El modo estándar moderno es usar el constructorKeyboardEvent(). KeyboardEvent.initKeyboardEvent()Obsoleto-
Inicializa un objeto
KeyboardEvent. Este método nunca fue implementado por Gecko (quien usaKeyboardEvent.initKeyEvent()) y no debe ser utilizado más. El modo estándar moderno es usar el constructorKeyboardEvent().
Propiedades
Esta interfaz también hereda propiedades de sus padres UIEvent y Event.
KeyboardEvent.altKeyRead only-
Devuelve un
Booleanque serátruesi la tecla Alt (Option or ⌥ on OS X) fue activada cuando el evento fue generado. KeyboardEvent.charNo estándar Obsoleto Read only-
Devuelve un
DOMStringrepresentando el valor del carácter de la tecla. Si la tecla corresponde con un carácter imprimible, este valor es una cadena Unicode no vacía que contiene este carácter. Si la tecla no tiene una representación imprimible, esta es una cadena vacía.Nota: Si la tecla es usada como una macro que inserta múltiples caracteres, If the key is used as a macro that inserts multiple characters, el valor de este atributo es la cadena completa, no solo el primer carácter.
Advertencia: Esta propiedad ha sido eliminada de los eventos del DOM de nivel 3. Esta es únicamente soportada en IE.
KeyboardEvent.charCodeObsoleto Read only-
Returns an
unsigned longrepresenting the Unicode reference number of the key; this attribute is used only by thekeypressevent. For keys whosecharattribute contains multiple characters, this is the Unicode value of the first character in that attribute. In Firefox 26 this returns codes for printable characters.Advertencia: This attribute is deprecated; you should use
keyinstead, if available. KeyboardEvent.codeRead only-
Returns a
DOMStringwith the code value of the key represented by the event. KeyboardEvent.ctrlKeyRead only-
Returns a
Booleanthat istrueif the Ctrl key was active when the key event was generated. KeyboardEvent.isComposingRead only-
Returns a
Booleanthat istrueif the event is fired between aftercompositionstartand beforecompositionend. KeyboardEvent.keyRead only-
Returns a
DOMStringrepresenting the key value of the key represented by the event. KeyboardEvent.keyCodeObsoleto Read only-
Returns an
unsigned longrepresenting a system and implementation dependent numerical code identifying the unmodified value of the pressed key.Advertencia: This attribute is deprecated; you should use
keyinstead, if available. KeyboardEvent.localeRead only-
Returns a
DOMStringrepresenting a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn't know the keyboard's locale.Nota: This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.
KeyboardEvent.locationRead only-
Returns an
unsigned longrepresenting the location of the key on the keyboard or other input device. KeyboardEvent.metaKeyRead only-
Returns a
Booleanthat istrueif the Meta (or Command on OS X) key was active when the key event was generated. KeyboardEvent.repeatRead only-
Returns a
Booleanthat istrueif the key is being held down such that it is automatically repeating. KeyboardEvent.shiftKeyRead only-
Returns a
Booleanthat istrueif the Shift key was active when the key event was generated. KeyboardEvent.whichObsoleto Read only-
Returns an
unsigned longrepresenting a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same askeyCode.Advertencia: This attribute is deprecated; you should use
keyinstead, if available.
Notes
There are keydown, keypress, and keyup events. For most keys, Gecko dispatches a sequence of key events like this:
- When the key is first depressed, the
keydownevent is sent. - If the key is not a modifier key, the
keypressevent is sent. - When the user releases the key, the
keyupevent is sent.
Special cases
Certain keys toggle the state of an LED indicator, such as Caps Lock, Num Lock, and Scroll Lock. On Windows and Linux, these keys dispatch only the keydown and keyup events. Note that on Linux, Firefox 12 and earlier also dispatched the keypress event for these keys.
On Mac, however, Caps Lock dispatches only the keydown event due to a platform event model limitation. Num Lock had been supported on old MacBook (2007 model and older) but Mac hasn't supported Num Lock feature even on external keyboards in these days. On the old MacBook which has Num Lock key, Num Lock doesn't cause any key events. And Gecko supports Scroll Lock key if an external keyboard which has F14 is connected. However, it generates keypress event. This inconsistent behavior is a bug; see Error 602812 en Firefox.
Auto-repeat handling
When a key is pressed and held down, it begins to auto-repeat. This results in a sequence of events similar to the following being dispatched:
keydownkeypresskeydownkeypress- <<repeating until the user releases the key>>
keyup
This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.
Auto-repeat on some GTK environments such as Ubuntu 9.4
In some GTK-based environments, auto-repeat dispatches a native key-up event automatically during auto-repeat, and there's no way for Gecko to know the difference between a repeated series of keypresses and an auto-repeat. On those platforms, then, an auto-repeat key will generate the following sequence of events:
keydownkeypresskeyupkeydownkeypresskeyup- <<repeating until the user releases the key>>
keyup
In these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.
Auto-repeat handling prior to Gecko 4.0
Before Gecko 4.0, keyboard handling was less consistent across platforms.
- Windows
-
Auto-repeat behavior is the same as in Gecko 4.0 and later.
- Mac
-
After the initial keydown event, only keypress events are sent until the keyup event occurs; the inter-spaced keydown events are not sent.
- Linux
-
The event behavior depends on the specific platform. It will either behave like Windows or Mac depending on what the native event model does.
Example
<!DOCTYPE html>
<html>
<head>
<script>
var metaChar = false;
var exampleKey = 16;
function keyEvent(event) {
var key = event.keyCode || event.which;
var keychar = String.fromCharCode(key);
if (key == exampleKey) {
metaChar = true;
}
if (key != exampleKey) {
if (metaChar) {
alert("Combination of metaKey + " + keychar);
metaChar = false;
} else {
alert("Key pressed " + key);
}
}
}
function metaKeyUp (event) {
var key = event.keyCode || event.which;
if (key == exampleKey) {
metaChar = false;
}
}
</script>
</head>
<body onkeydown="keyEvent(event)" onkeyup="metaKeyUp(event)">
</body>
</html>
Especificaciones
| Specification |
|---|
| UI Events> # interface-keyboardevent> |
Compatibilidad con navegadores
Loading…