2012-07-10 18 views
6

Estamos creando una interfaz de usuario web que se parece a una ventana de escritorio. Ahora tenemos que manejar la clave Alt. Cuando se presiona Alt, el foco va al menú superior.javascript alt key

En Javascript, cómo sacar el caso de Alt tecla cuando se pulsa la tecla Alt SOLO ? Necesito asegurarme de que no se presionó ninguna otra tecla al mismo tiempo.

Gracias de antemano.

+0

¿Mi solución es útil? – Talha

Respuesta

2

No sé si esta es la solución más elegante, pero funcionó bien.

$(function() 
{ 
    //Flag to check if another key was pressed with alt 
    var vAnotherKeyWasPressed = false; 
    //ALT keycode const 
    var ALT_CODE = 18; 

    //When some key is pressed 
    $(window).keydown(function(event) 
    { 
     //Identifies the key 
     var vKey = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; 
     //The last key pressed is alt or not? 
     vAnotherKeyWasPressed = vKey != ALT_CODE; 
    }); 

    //When some key is left 
    $(window).keyup(function(event) 
    { 
     //Identifies the key 
     var vKey = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; 

     //If the key left is ALT and no other key is pressed at the same time... 
     if (!vAnotherKeyWasPressed && vKey == ALT_CODE) 
     { 
      //Focus the menu 
      $('#myMenu').focus(); 
      //Stop the events for the key to avoid windows set the focus to the browser toolbar 
      return false; 
     } 
    }); 
}); 
+0

esta solución parece ser la mejor solución de todas hasta el momento debido a que será compatible con más navegadores. No todos los navegadores entienden event.keyCode. Algunos usan event.which. Esta solución lo cubre todo. – James

8

tal como esto

document.onkeydown = keydown; 

function keydown(evt) { 
    if (!evt) evt = event; 
    if (evt.altKey) { 
     alert('alt'); 
    } 
} // function keydown(evt)​ 
+0

también hay algo como: evt.ctrlKey (para ctrl) – Ricky

5

Trabajando Demo

document.onkeyup = KeyCheck;  

function KeyCheck(e) 
{ 
    var KeyID = (window.event) ? event.keyCode : e.keyCode; 
    switch(KeyID) 
    { 
     case 18: 
     document.Form1.KeyName.value = "Alt"; 
     // do your work on alt key press.... 
     break; 

     case 17: 
     document.Form1.KeyName.value = "Ctrl"; 
     break; 
    } 
} 

Y su html puede ser así

<form name="Form1"> 

<input type="text" name="KeyName" value="" /> 

</form>​ 

Nota: Si desea obtener el alt evento en otro control/tipo que lo modifica con sus requisitos.

+1

Gracias por la respuesta, pero el evento sigue levantándose si se presiona otra tecla al mismo tiempo (como Alt + L). Además, la función debe devolver falso porque cuando se presiona la tecla alt, Windows pone el foco en la barra de herramientas del navegador. – Riera