From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- .../api/keyboardevent/getmodifierstate/index.html | 253 ++++++++++++ files/es/web/api/keyboardevent/index.html | 441 +++++++++++++++++++++ files/es/web/api/keyboardevent/key/index.html | 212 ++++++++++ files/es/web/api/keyboardevent/metakey/index.html | 131 ++++++ files/es/web/api/keyboardevent/which/index.html | 62 +++ 5 files changed, 1099 insertions(+) create mode 100644 files/es/web/api/keyboardevent/getmodifierstate/index.html create mode 100644 files/es/web/api/keyboardevent/index.html create mode 100644 files/es/web/api/keyboardevent/key/index.html create mode 100644 files/es/web/api/keyboardevent/metakey/index.html create mode 100644 files/es/web/api/keyboardevent/which/index.html (limited to 'files/es/web/api/keyboardevent') diff --git a/files/es/web/api/keyboardevent/getmodifierstate/index.html b/files/es/web/api/keyboardevent/getmodifierstate/index.html new file mode 100644 index 0000000000..b44ecc6da3 --- /dev/null +++ b/files/es/web/api/keyboardevent/getmodifierstate/index.html @@ -0,0 +1,253 @@ +--- +title: KeyboardEvent.getModifierState() +slug: Web/API/KeyboardEvent/getModifierState +tags: + - API + - DOM + - KeyboardEvent + - Referencia + - getModifierState + - metodo +translation_of: Web/API/KeyboardEvent/getModifierState +--- +

{{APIRef("DOM Events")}}

+ +

El método KeyboardEvent.getModifierState() retorna true respecto al estado actual de la tecla modificadora especificada si la misma está presionada o bloqueada, en caso contrario devuelve false.

+ +

Sintaxis

+ +
var active = event.getModifierState(keyArg);
+ +

Retorna

+ +

A {{jsxref("Boolean")}}

+ +

Parámetros

+ +
+
keyArg
+
El valor de la tecla modificadora. El valor debe ser uno de los valores {{domxref("KeyboardEvent.key")}} que representan las teclas modificadoras, o el string "Accel" {{deprecated_inline}}, el cual es case-sensitive.
+
+ +

Teclas modificadoras en Internet Explorer

+ +

IE9 usa "Scroll" para "ScrollLock" y "Win" para "OS".

+ +

Teclas modificadoras en Gecko

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
When getModifierState() returns true on Gecko?
 WindowsLinux (GTK)MacAndroid 2.3Android 3.0 or latter
"Alt"Either Alt key or AltGr key pressedAlt key pressed⌥ Option key pressedAlt key or option key pressed
"AltGraph" +

Both Alt and Ctrl keys are pressed, or AltGr key is pressed

+
Level 3 Shift key (or Level 5 Shift key {{gecko_minversion_inline("20.0")}}) pressed⌥ Option key pressedNot supported
"CapsLock"During LED for ⇪ Caps Lock turned onNot supportedWhile CapsLock is locked {{gecko_minversion_inline("29.0")}}
"Control"Either Ctrl key or AltGr key pressedCtrl key pressedcontrol key pressedmenu key pressed.Ctrl key, control key or menu key pressed.
"Fn"Not supportedFunction key is pressed, but we're not sure what key makes the modifier state active. Fn key on Mac keyboard doesn't cause this active. {{gecko_minversion_inline("29.0")}}
"FnLock"Not supported
"Hyper"Not supported
"Meta"Not supportedMeta key pressed {{gecko_minversion_inline("17.0")}}⌘ Command key pressedNot supported⊞ Windows Logo key or command key pressed
"NumLock"During LED for Num Lock turned onA key on numpad pressedNot supportedWhile NumLock is locked {{gecko_minversion_inline("29.0")}}
"OS"⊞ Windows Logo key pressedSuper key or Hyper key pressed (typically, mapped to ⊞ Windows Logo key)Not supported
"ScrollLock"During LED for Scroll Lock turned onDuring LED for Scroll Lock turned on, but typically this isn't supported by platformNot supportedWhile ScrollLock is locked {{gecko_minversion_inline("29.0")}}
"Shift"⇧ Shift key pressed
"Super"Not supported
"Symbol"Not supported
"SymbolLock"Not supported
+ + + +

 El modificador virtual "Accel"

+ +
Note: The "Accel" virtual modifier has been effectively deprecated in current drafts of the DOM3 Events specification.
+ +

getModifierState() also accepts a deprecated virtual modifier named "Accel". event.getModifierState("Accel") returns true when at least one of {{domxref("KeyboardEvent.ctrlKey")}} or {{domxref("KeyboardEvent.metaKey")}} is true.

+ +

In old implementations and outdated specifications, it returned true when a modifier which is the typical modifier key for the shortcut key is pressed. For example, on Windows, pressing Ctrl key may make it return true. However, on Mac, pressing ⌘ Command key may make it return true. Note that which modifier key makes it return true depends on platforms, browsers, and user settings. For example, Firefox users can customize this with a pref, "ui.key.accelKey".

+ +

Ejemplo

+ +
// Ignore if following modifier is active.
+if (event.getModifierState("Fn") ||
+    event.getModifierState("Hyper") ||
+    event.getModifierState("OS") ||
+    event.getModifierState("Super") ||
+    event.getModifierState("Win") /* hack for IE */) {
+  return;
+}
+
+// Also ignore if two or more modifiers except Shift are active.
+if (event.getModifierState("Control") +
+    event.getModifierState("Alt") +
+    event.getModifierState("Meta") > 1) {
+  return;
+}
+
+// Handle shortcut key with standard modifier
+if (event.getModifierState("Accel")) {
+  switch (event.key.toLowerCase()) {
+    case "c":
+      if (event.getModifierState("Shift")) {
+        // Handle Accel + Shift + C
+        event.preventDefault(); // consume the key event
+      }
+      break;
+    case "k":
+      if (!event.getModifierState("Shift")) {
+        // Handle Accel + K
+        event.preventDefault(); // consume the key event
+      }
+      break;
+  }
+  return;
+}
+
+// Do somethig different for arrow keys if ScrollLock is locked.
+if ((event.getModifierState("ScrollLock") ||
+       event.getModifierState("Scroll") /* hack for IE */) &&
+    !event.getModifierState("Control") &&
+    !event.getModifierState("Alt") &&
+    !event.getModifierState("Meta")) {
+  switch (event.key) {
+    case "ArrowDown":
+    case "Down": // hack for IE and old Gecko
+      event.preventDefault(); // consume the key event
+      break;
+    case "ArrowLeft":
+    case "Left": // hack for IE and old Gecko
+      // Do something different if ScrollLock is locked.
+      event.preventDefault(); // consume the key event
+      break;
+    case "ArrowRight":
+    case "Right": // hack for IE and old Gecko
+      // Do something different if ScrollLock is locked.
+      event.preventDefault(); // consume the key event
+      break;
+    case "ArrowUp":
+    case "Up": // hack for IE and old Gecko
+      // Do something different if ScrollLock is locked.
+      event.preventDefault(); // consume the key event
+      break;
+  }
+}
+
+ +
+

Although, this example uses .getModifierState() with "Alt", "Control", "Meta" and "Shift", perhaps it's better for you to use altKey, ctrlKey, metaKey and shiftKey because they are shorter and may be faster.

+
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificacionesEstadoComentario
{{SpecName('DOM3 Events', '#widl-KeyboardEvent-getModifierState', 'getModifierState()')}}{{Spec2('DOM3 Events')}}Initial definition (Modifier Keys spec)
+ +

Compatibilidad con Browsers

+ + + +

{{Compat("api.KeyboardEvent.getModifierState")}}

+ +

Ver también

+ + diff --git a/files/es/web/api/keyboardevent/index.html b/files/es/web/api/keyboardevent/index.html new file mode 100644 index 0000000000..bcb27d00b6 --- /dev/null +++ b/files/es/web/api/keyboardevent/index.html @@ -0,0 +1,441 @@ +--- +title: KeyboardEvent +slug: Web/API/KeyboardEvent +tags: + - API +translation_of: Web/API/KeyboardEvent +--- +

{{APIRef("DOM Events")}}

+ +

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

+ +
+
{{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}
+
Crea un objeto KeyboardEvent.
+
+ +

Métodos

+ +

Esta interfaz también hereda métodos de sus padres, {{domxref("UIEvent")}} and {{domxref("Event")}}.

+ +
+
{{domxref("KeyboardEvent.getModifierState()")}}
+
Devuelve un {{jsxref("Boolean")}} indicando si una tecla modificadora, como AltShiftCtrl, o Meta, fue pulsada cuando el evento fue creado.
+
{{domxref("KeyboardEvent.initKeyEvent()")}}{{deprecated_inline}}
+
Inicializa un objeto KeyboardEvent. Este método solo ha sido implementado por Gecko (otros usados {{domxref("KeyboardEvent.initKeyboardEvent()")}}) y nunca más será usado. El modo estándar moderno es usar el constructor {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.
+
{{domxref("KeyboardEvent.initKeyboardEvent()")}}{{deprecated_inline}}
+
Inicializa un objeto KeyboardEvent. Este método nunca fue implementado por Gecko (quien usa {{domxref("KeyboardEvent.initKeyEvent()")}}) y no debe ser utilizado más. El modo estándar moderno es usar el constructor {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.
+
+ +

Propiedades

+ +

Esta interfaz también hereda propiedades de sus padres {{domxref("UIEvent")}} y {{domxref("Event")}}.

+ +
+
{{domxref("KeyboardEvent.altKey")}} {{Readonlyinline}}
+
Devuelve un {{jsxref("Boolean")}} que será true si la tecla Alt ( Option or on OS X) fue activada cuando el evento fue generado.
+
{{domxref("KeyboardEvent.char")}} {{Non-standard_inline()}}{{Deprecated_inline}}{{Readonlyinline}}
+
Devuelve un {{domxref("DOMString")}} representando 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.
+
+
{{domxref("KeyboardEvent.charCode")}} {{Deprecated_inline}}{{Readonlyinline}}
+
Returns an unsigned long representing the Unicode reference number of the key; this attribute is used only by the keypress event. For keys whose char attribute contains multiple characters, this is the Unicode value of the first character in that attribute. In Firefox 26 this returns codes for printable characters. +
Warning: This attribute is deprecated; you should use key instead, if available.
+
+
{{domxref("KeyboardEvent.code")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} with the code value of the key represented by the event.
+
{{domxref("KeyboardEvent.ctrlKey")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the Ctrl key was active when the key event was generated.
+
{{domxref("KeyboardEvent.isComposing")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the event is fired between after compositionstart and before compositionend.
+
{{domxref("KeyboardEvent.key")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} representing the key value of the key represented by the event.
+
{{domxref("KeyboardEvent.keyCode")}} {{deprecated_inline()}}{{Readonlyinline}}
+
Returns an unsigned long representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key. +
Warning: This attribute is deprecated; you should use key instead, if available.
+
+
{{domxref("KeyboardEvent.locale")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} representing 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. +
Note: 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.
+
+
{{domxref("KeyboardEvent.location")}} {{Readonlyinline}}
+
Returns an unsigned long representing the location of the key on the keyboard or other input device.
+
{{domxref("KeyboardEvent.metaKey")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the Meta (or Command on OS X) key was active when the key event was generated.
+
{{domxref("KeyboardEvent.repeat")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the key is being held down such that it is automatically repeating.
+
{{domxref("KeyboardEvent.shiftKey")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the Shift key was active when the key event was generated.
+
{{domxref("KeyboardEvent.which")}} {{deprecated_inline}}{{Readonlyinline}}
+
Returns an unsigned long representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode. +
Warning: This attribute is deprecated; you should use key instead, if available.
+
+
+ +

Notes

+ +

There are keydown, keypress, and keyup events. For most keys, Gecko dispatches a sequence of key events like this:

+ +
    +
  1. When the key is first depressed, the keydown event is sent.
  2. +
  3. If the key is not a modifier key, the keypress event is sent.
  4. +
  5. When the user releases the key, the keyup event is sent.
  6. +
+ +

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 {{bug(602812)}}.

+ +

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:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. keydown
  6. +
  7. keypress
  8. +
  9. <<repeating until the user releases the key>>
  10. +
  11. keyup
  12. +
+ +

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:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. keyup
  6. +
  7. keydown
  8. +
  9. keypress
  10. +
  11. keyup
  12. +
  13. <<repeating until the user releases the key>>
  14. +
  15. keyup
  16. +
+ +

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 {{geckoRelease('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>
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events', '#interface-KeyboardEvent', 'KeyboardEvent')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

The KeyboardEvent interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, {{domxref("KeyboardEvent.initKeyEvent()")}} by Gecko browsers and the early DOM Events Level 3 version, {{domxref("KeyboardEvent.initKeyboardEvent()")}} by others. Both have been superseded by the modern usage of a constructor: {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.

+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
constructor{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("31.0") }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
.char{{ CompatNo() }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}
.charCode{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
.codeSee Browser compatibility of {{domxref("KeyboardEvent.code")}}.
.isComposing{{ CompatNo() }}{{ CompatGeckoDesktop("31.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
.keySee Browser compatibility of {{domxref("KeyboardEvent.key")}}.
.keyCode{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
.locale{{ CompatNo() }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}
.location{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("15.0") }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}
.repeat{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("28.0") }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}
.which{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
.getModifierState()See Browser compatibility of {{domxref("KeyboardEvent.getModifierState")}}
.initKeyboardEvent(){{ CompatVersionUnknown() }} *1{{ CompatNo() }} *2{{ CompatIE("9.0") }} *3{{ CompatUnknown() }}{{ CompatVersionUnknown() }} *1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
constructor{{ CompatUnknown() }}{{ CompatGeckoMobile("31.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
.char{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
.charCode{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
.codeSee Browser compatibility of {{domxref("KeyboardEvent.code")}}.
.isComposing{{ CompatNo() }}{{ CompatGeckoMobile("31.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
.keySee Browser compatibility table of {{domxref("KeyboardEvent.key")}}.
.keyCode{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
.locale{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
.location{{ CompatUnknown() }}{{ CompatGeckoMobile("15.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
.repeat{{ CompatUnknown() }}{{ CompatGeckoMobile("28.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
.which{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
.getModifierState()See Browser compatibility of {{domxref("KeyboardEvent.getModifierState")}}
.initKeyboardEvent(){{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +


+ *1 The arguments of initKeyboardEvent() of WebKit and Blink's are different from the definition in DOM Level 3 Events. The method is: initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg,  in views::AbstractView viewArg, in DOMString keyIndentifierArg, in unsigned long locationArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in boolean altGraphKeyArg)

+ +

*2 Gecko won't support initKeyboardEvent() because supporting it completely breaks feature detection of web applications. See {{Bug(999645)}}.

+ +

*3 The argument of initKeyboardEvent() of IE is different from the definition in DOM Level 3 Events. The method is: initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyArg, in unsigned long locationArg, in DOMString modifierListArg, in boolean repeatArt, in DOMString locationArg). See document of initKeyboardEvent() in MSDN.

diff --git a/files/es/web/api/keyboardevent/key/index.html b/files/es/web/api/keyboardevent/key/index.html new file mode 100644 index 0000000000..ed765b38b3 --- /dev/null +++ b/files/es/web/api/keyboardevent/key/index.html @@ -0,0 +1,212 @@ +--- +title: KeyboardEvent.key +slug: Web/API/KeyboardEvent/key +translation_of: Web/API/KeyboardEvent/key +--- +

{{APIRef("DOM Events")}}

+ +

La propiedad de solo lectura KeyboardEvent.key retorna el valor de la tecla presionada por el usuario while taking into considerations the state of modifier keys such as the shiftKey as well as the keyboard locale/layout. Its value is determined as follows:

+ +
+

See a full list of key values.

+
+ + + +

KeyboardEvent Sequence

+ +

KeyboardEvents are fired in a pre-determined sequence and understanding this will go a long way into understanding the key property value for a particular KeyboardEvent. For a given key press, the sequence of KeyboardEvents fired is as follows assuming that {{domxref("Event.preventDefault")}} is not called:

+ +
    +
  1. A {{event("keydown")}} event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the {{domxref("KeyboardEvent.repeat")}} read only property  is set to true.
  2. +
  3. If the key produces a character key that would result in a character being inserted into possibly an {{HTMLElement("input")}}, {{HTMLElement("textarea")}} or an element with {{domxref("HTMLElement.contentEditable")}} set to true, the {{event("beforeinput")}} and {{event("input")}} event types are fired in that order. Note that some other implementations may fire {{event("keypress")}} event if supported. The events will be fired repeatedly while the key is held down.
  4. +
  5. A {{event("keyup")}} event is fired once the key is released. This completes the process.
  6. +
+ +

In sequence 1 & 3, the KeyboardEvent.key attribute is defined and is set appropriately to a value according to the rules defined ealier.

+ +

KeyboardEvent Sequence Sample

+ +

Consider the event sequence generated when we interact with the ShiftKey and the legend key 2 using a U.S keyboard layout and a UK keyboard layout.

+ +

Try experimenting using the following two test cases:

+ +
    +
  1. Press and hold the shift key, then press key 2 and release it. Next, release the shift key.
  2. +
  3. Press and hold the shift key, then press and hold key 2. Release the shift key. Finally, release key 2.
  4. +
+ +

HTML

+ +
<div class="fx">
+  <div>
+    <textarea rows="5" name="test-target" id="test-target"></textarea>
+    <button type="button" name="btn-clear-console" id="btn-clear-console">clear console</button>
+  </div>
+  <div class="flex">
+    <div id="console-log"></div>
+  </div>
+</div>
+
+ +

CSS

+ +
.fx {
+  -webkit-display: flex;
+  display: flex;
+  margin-left: -20px;
+  margin-right: -20px;
+}
+
+.fx > div {
+  padding-left: 20px;
+  padding-right: 20px;
+}
+
+.fx > div:first-child {
+   width: 30%;
+}
+
+.flex {
+  -webkit-flex: 1;
+  flex: 1;
+}
+
+#test-target {
+  display: block;
+  width: 100%;
+  margin-bottom: 10px;
+}
+ +

JavaScript

+ +
let textarea = document.getElementById('test-target'),
+consoleLog = document.getElementById('console-log'),
+btnClearConsole = document.getElementById('btn-clear-console');
+
+function logMessage(message) {
+  let p = document.createElement('p');
+  p.appendChild(document.createTextNode(message));
+  consoleLog.appendChild(p);
+}
+
+textarea.addEventListener('keydown', (e) => {
+  if (!e.repeat)
+    logMessage(`first keydown event. key property value is "${e.key}"`);
+  else
+    logMessage(`keydown event repeats. key property value is "${e.key}"`);
+});
+
+textarea.addEventListener('beforeinput', (e) => {
+  logMessage(`beforeinput event. you are about inputing "${e.data}"`);
+});
+
+textarea.addEventListener('input', (e) => {
+  logMessage(`input event. you have just inputed "${e.data}"`);
+});
+
+textarea.addEventListener('keyup', (e) => {
+  logMessage(`keyup event. key property value is "${e.key}"`);
+});
+
+btnClearConsole.addEventListener('click', (e) => {
+  let child = consoleLog.firstChild;
+  while (child) {
+   consoleLog.removeChild(child);
+   child = consoleLog.firstChild;
+  }
+});
+ +

Result

+ +

{{EmbedLiveSample('KeyboardEvent_Sequence_Sample')}}

+ +

Case 1

+ +

When the shift key is pressed, a {{event("keydown")}} event is first fired, and the key property value is set to the string "Shift". As we keep holding this key, the {{event("keydown")}} event does not continue to fire repeatedly because it does not produce a character key.

+ +

When key 2 is pressed, another {{event("keydown")}} event is fired for this new key press, and the key property value for the event is set to the string "@" for the U.S keyboard type and """ for the UK keyboard type, because of the active modifier shift key. The {{event("beforeinput")}} and {{event("input")}} events are fired next because a character key has been produced.

+ +

As we release the key 2, a {{event("keyup")}} event is fired and the key property will maintain the string values "@" and """ for the different keyboard layouts respectively.

+ +

As we finally release the shift key, another {{event("keyup")}} event is fired for it, and the key attribute value remains "Shift".

+ +

Case 2

+ +

When the shift key is pressed, a {{event("keydown")}} event is first fired, and the key property value is set to be the string "Shift". As we keep holding this key, the keydown event does not continue to fire repeatedly because it produced no character key.

+ +

When key 2 is pressed, another {{event("keydown")}} event is fired for this new key press, and the key property value for the event is set to be the string "@" for the U.S keyboard type and """ for the UK keyboard type, because of the active modifier shift key. The {{event("beforeinput")}} and {{event("input")}} events are fired next because a character key has been produced. As we keep holding the key, the {{event("keydown")}} event continues to fire repeatedly and the {{domxref("KeyboardEvent.repeat")}}  property is set to true. The {{event("beforeinput")}} and {{event("input")}} events are fired repeatedly as well.

+ +

As we release the shift key, a {{event("keyup")}} event is fired for it, and the key attribute value remains "Shift". At this point, notice that the key property value for the repeating keydown event of the key 2 key press is now "2" because the modifier shift key is no longer active. The same goes for the {{domxref("InputEvent.data")}} property of the {{event("beforeinput")}} and {{event("input")}} events.

+ +

As we finally release the key 2, a {{event("keyup")}} event is fired but the key property will be set to the string value "2" for both keyboard layouts because the modifier shift key is no longer active.

+ +

Example

+ +

This example uses {{domxref("EventTarget.addEventListener()")}} to listen for {{event("keydown")}} events. When they occur,  the key's value is checked to see if it's one of the keys the code is interested in, and if it is, it gets processed in some way (possibly by steering a spacecraft, perhaps by changing the selected cell in a spreadsheet).

+ +
window.addEventListener("keydown", function (event) {
+  if (event.defaultPrevented) {
+    return; // Do nothing if the event was already processed
+  }
+
+  switch (event.key) {
+    case "Down": // IE specific value
+    case "ArrowDown":
+      // Do something for "down arrow" key press.
+      break;
+    case "Up": // IE specific value
+    case "ArrowUp":
+      // Do something for "up arrow" key press.
+      break;
+    case "Left": // IE specific value
+    case "ArrowLeft":
+      // Do something for "left arrow" key press.
+      break;
+    case "Right": // IE specific value
+    case "ArrowRight":
+      // Do something for "right arrow" key press.
+      break;
+    case "Enter":
+      // Do something for "enter" or "return" key press.
+      break;
+    case "Escape":
+      // Do something for "esc" key press.
+      break;
+    default:
+      return; // Quit when this doesn't handle the key event.
+  }
+
+  // Cancel the default action to avoid it being handled twice
+  event.preventDefault();
+}, true);
+
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events', '#widl-KeyboardEvent-key', 'KeyboardEvent.key')}}{{Spec2('DOM3 Events')}}Initial definition, included key values.
+ +

Browser compatibility

+ + + +

{{Compat("api.KeyboardEvent.key")}}

diff --git a/files/es/web/api/keyboardevent/metakey/index.html b/files/es/web/api/keyboardevent/metakey/index.html new file mode 100644 index 0000000000..7a83c5c0b2 --- /dev/null +++ b/files/es/web/api/keyboardevent/metakey/index.html @@ -0,0 +1,131 @@ +--- +title: KeyboardEvent.metaKey +slug: Web/API/KeyboardEvent/metaKey +tags: + - Evento + - Referencia +translation_of: Web/API/KeyboardEvent/metaKey +--- +

{{APIRef("DOM Events")}}

+ +

La propiedad KeyboardEvent.metaKey  es de solo lectura y regresa un valor {{jsxref("Boolean")}} que indica si la tecla Meta estaba presionada (true) o no (false) cuando el evento ocurrio.

+ +
+

Nota: En teclados Macintosh es la tecla comando (). En teclados Windows la tecla es lla tecla window ().

+
+ +

Syntax

+ +
var metaKeyPressed = instanceOfKeyboardEvent.metaKey
+
+ +

Valor de retorno

+ +

{{jsxref("Boolean")}}

+ +

Ejemplo

+ +
 function goInput(e) {
+ // Revisa si estaba presionada la tecla meta y
+   if (e.metaKey) {
+        // realiza esto en caso de cierto
+     superSizeOutput(e);
+   } else {
+         //Realiz esto en caso de falso
+     doOutput(e);
+   }
+ }
+
+ +

metaKey

+ +

Contenido HTML

+ +
<div id="example" onmousedown="ismetaKey(event);">¡Presiona la tecla meta y dame click!<div>
+
+ +

Contenido Javascript

+ +
function ismetaKey(e){
+ var el=document.getElementById("example");//Toma el control del div example
+ var mK=e.metaKey;//Obtiene el valor de metaKey y lo almacena
+ el.innerHTML="¡Presiona la tecla meta y dame click!</br>metaKey:"+mK;//Muestra el valor de metaKey
+}
+
+ +

 

+ +

{{ EmbedLiveSample('metaKey') }}

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónStatusComentario
{{SpecName('DOM3 Events','#widl-KeyboardEvent-metaKey','KeyboardEvent.metaKey')}}{{Spec2('DOM3 Events')}}Definición inicial
+ +

Compatibilidad de Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Soporte Básico{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Soporte Básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Ver también

+ + diff --git a/files/es/web/api/keyboardevent/which/index.html b/files/es/web/api/keyboardevent/which/index.html new file mode 100644 index 0000000000..11e1e3e48e --- /dev/null +++ b/files/es/web/api/keyboardevent/which/index.html @@ -0,0 +1,62 @@ +--- +title: event.which +slug: Web/API/KeyboardEvent/which +tags: + - DOM + - events + - metodo + - which +translation_of: Web/API/KeyboardEvent/which +--- +

{{ ApiRef() }}

+

Resumen

+

Devuelve el keyCode de la tecla presionada, o el codigo del caracter (charCode) de la tecla alfanumerica presionada.

+

Sintaxis

+
var keyResult = event.which;
+
+

keyResult contiene el codigo numerico para una tecla en particular, dependiendo si la tecla presionada es alfanumerica o no-alfanumerica. Por favor mire charCode y keyCode para mas informacion.

+

Ejemplo

+
<html>
+<head>
+<title>charCode/keyCode/which example</title>
+
+<script type="text/javascript">
+
+function showKeyPress(evt)
+{
+alert("onkeypress handler: \n"
+      + "keyCode property: " + evt.keyCode + "\n"
+      + "which property: " + evt.which + "\n"
+      + "charCode property: " + evt.charCode + "\n"
+      + "Character Key Pressed: "
+      + String.fromCharCode(evt.charCode) + "\n"
+     );
+}
+
+
+function keyDown(evt)
+{
+alert("onkeydown handler: \n"
+      + "keyCode property: " + evt.keyCode + "\n"
+      + "which property: " + evt.which + "\n"
+     );
+}
+
+
+</script>
+</head>
+
+<body
+ onkeypress="showKeyPress(event);"
+ onkeydown="keyDown(event);"
+>
+
+<p>Por favor presione cualquier tecla.</p>
+
+</body>
+</html>
+
+
+ Nota: El codigo de arriba falla en Firefox 9 debido al bug 696020.
+

Especificacion

+

No es parte de ninguna especificacion.

-- cgit v1.2.3-54-g00ecf