2010-06-26 10 views
6
<html> 
<head> 
<title>Test</title> 

<script type="text/javascript"> 

function showChar(e) { 
    if (e.keyCode != 16) { 
     alert(
      "keyCode: " + e.keyCode + "\n" 
      + "SHIFT key pressed: " + e.shiftKey + "\n" 
     ); 
    } 
} 

</script> 
</head> 

<body onkeydown="showChar(event);"> 
<p>Press any character key, with or without holding down 
the SHIFT key.<br /></p> 
</body> 
</html> 

¿Cómo puedo diferenciar el capital Un de minúsculas un en el método controlador de eventos onkeydown? El algoritmo anterior dispara el mismo valor de código de clave. Necesito detectar las letras mayúsculas cuando están presionadas enkeydown.cómo diferenciar mayúsculas de las inferiores en el método de control de eventos onkeydown

Nota: El código contiene una excepción para la tecla MAYÚS. De lo contrario, no permite escribir letras mayúsculas. Por cierto, necesito usar onkeydown para mi prueba.

Respuesta

6

Me parece que ha respondido a su propia pregunta. Si está detectando la tecla SHIFT, podrá distinguir entre el capital y minúsculas:

if(e.shiftKey){ 
    alert("You pressed a CAPITAL letter with the code " + e.keyCode); 
}else{ 
    alert("You pressed a LOWERCASE letter with the code " + e.keyCode); 
} 

o estoy malentendido su pregunta?

Actualización: códigos caso ASCII superiores se pueden convertir fácilmente para bajar códigos caso ASCII mediante la adición de 32, por lo que todo lo que necesita hacer es lo siguiente:

<html> 
<head> 
<title>Test</title> 

<script type="text/javascript"> 

function showChar(e){ 
    if(e.keyCode!=16){ // If the pressed key is anything other than SHIFT 
     if(e.keyCode >= 65 && e.keyCode <= 90){ // If the key is a letter 
      if(e.shiftKey){ // If the SHIFT key is down, return the ASCII code for the capital letter 
       alert("ASCII Code: "+e.keyCode); 
      }else{ // If the SHIFT key is not down, convert to the ASCII code for the lowecase letter 
       alert("ASCII Code: "+(e.keyCode+32)); 
      } 
     }else{ 
      alert("ASCII Code (non-letter): "+e.keyCode); 
     } 
    } 
} 

</script> 
</head> 

<body onkeydown="showChar(event);"> 
<p>Press any character key, with or without holding down 
the SHIFT key.<br /></p> 
</body> 
</html> 

Actualización 2: Prueba esto:

<html> 
<head> 
<title>Test</title> 

<script type="text/javascript"> 

function showChar(e){ 
    if(e.keyCode!=16){ // If the pressed key is anything other than SHIFT 
     c = String.fromCharCode(e.keyCode); 
     if(e.shiftKey){ // If the SHIFT key is down, return the ASCII code for the capital letter 
      alert("ASCII Code: "+e.keyCode+" Character: "+c); 
     }else{ // If the SHIFT key is not down, convert to the ASCII code for the lowecase letter 
      c = c.toLowerCase(c); 
      alert("ASCII Code: "+c.charCodeAt(0)+" Character: "+c); 
     } 
    } 
} 

</script> 
</head> 

<body onkeydown="showChar(event);"> 
<p>Press any character key, with or without holding down 
the SHIFT key.<br /></p> 
</body> 
</html> 
+0

Pero no debería cambiar el código clave, también? Necesito diferenciar de keyCode u otra cosa como valor. En ambos ejemplos, el código clave es el mismo. Busco una forma que proporcione una clave diferenteCódigos para mayúscula A y minúscula a presionada. –

+0

Echa un vistazo a la actualización de mi respuesta anterior. Creo que eso es lo que estás buscando. – Computerish

+0

Gracias eso es bastante cercano a mi necesidad. Pero, ¿cómo puedo agregar soporte para UTF-8? Digamos por capital Ü y smallcase ü arroja la alerta "ASCII Code (non-letter)". ¿Es posible diferenciar las letras de Unicode de las pequeñas letras en onkeydown? –

1

Hice un poco de búsqueda sobre esta cuestión, ya que estaba escribiendo código para limitar un elemento de entrada (utilizando el evento keyPress) a caracteres alfabéticos solamente. Estaba usando "códigos de caracteres entre 65 y 90" y no pude ingresar letras minúsculas en el campo.

Finalmente descubrí que JavaScript está usando códigos ASCII para esto, así que acabo de agregar "y también entre 97 y 122" y viola! Puedo ingresar letras mayúsculas y minúsculas. A saber:

function alphaOnly(e) { 
    'use strict'; 
    if (!e) { // compensates for IE's key code reporting. 
     e = window.event; 
    } 
    var charCode = (e.which) ? e.which : event.keyCode; 
    if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) { 
     return true; 
    } else { 
     return false; 
    } 
} 
0

Más reciente y mucho más limpio: use event.key. ¡No más códigos de números arbitrarios!

node.addEventListener('keydown', function(event) { 
    const key = event.key; // "a", "1", "Shift", etc. 
    if (/^[a-z]$/i.test(key)) { // or if (key.length === 1 && /[a-z]/i.test(key)) 
     const isCapital = event.shiftKey; 
    } 
}); 

Mozilla Docs

Supported Browsers

Cuestiones relacionadas