2012-07-10 16 views
6

Stiamo creando un'interfaccia utente Web simile a una finestra del desktop. Ora dobbiamo gestire la chiave Alt. Quando viene premuto il tasto Alt, lo stato attivo passa al menu superiore.javascript alt key

in JavaScript, come ottenere l'evento per Alt chiave quando viene premuto solo Alt chiave? Devo assicurarmi che nessun altro tasto sia stato premuto allo stesso tempo.

Grazie in anticipo.

+0

La soluzione è utile? – Talha

risposta

2

Non so se questa è la soluzione più elegante, ma ha funzionato bene.

$(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

questa soluzione sembra essere la soluzione migliore da tutti loro fino ad ora perché sarà compatibile con altri browser. Non tutti i browser comprendono event.keyCode. Alcuni usano event.which. Questa soluzione copre tutto. – James

8

forse come questo

document.onkeydown = keydown; 

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

ci sono anche qualcosa di simile: evt.ctrlKey (per ctrl) – Ricky

5

Lavorare 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; 
    } 
} 

E il tuo HTML può essere come quello

<form name="Form1"> 

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

</form>​ 

Nota: Se si desidera ottenere l'alt evento su altro controllo/tipo che modificarlo con le vostre esigenze.

+1

Grazie per la risposta, ma l'evento è ancora sollevato se viene premuto un altro tasto allo stesso tempo (come Alt + L). Inoltre, la funzione deve restituire false perché quando viene premuto il tasto alt, Windows mette a fuoco nella barra degli strumenti del browser. – Riera