2012-02-21 14 views
31

Qui vedo alcune domande simili (come JavaScript: Check if CTRL button was pressed) ma il mio problema è in realtà l'attivazione dell'evento. Il mio codice js:javascript - rileva il tasto ctrl premuto o su, l'evento keypress non si attiva

// Listen to keyboard. 
    window.onkeypress = listenToTheKey; 
    window.onkeyup = listenToKeyUp; 

    /* 
     Gets the key pressed and send a request to the associated function 
     @input key 
    */ 
    function listenToTheKey(e) 
    { 
     if (editFlag == 0) 
     { 
      // If delete key is pressed calls delete 
      if (e.keyCode == 46) 
       deleteNode(); 

      // If insert key is pressed calls add blank 
      if (e.keyCode == 45) 
       createBlank(); 

      if (e.keyCode == 17) 
       ctrlFlag = 1; 
     } 
    } 

L'evento attiva per tutti gli altri tasti ad eccezione del ctrl.
Devo anche attivarlo per ctrl.
Non riesco a utilizzare jQuery/prototipo/qualsiasi, quindi tali soluzioni non sono accettabili.

Quindi ... come posso rilevare lo ctrl?

+1

no: if (e.ctrlKey) {....} funziona ..? –

risposta

15

vostro evento ha una proprietà denominata ctrlKey. È possibile controllare questo per vedere se il tasto è stato premuto o meno. Vedi lo snippet qui sotto per maggiori controlli come i tasti.

function detectspecialkeys(e){ 
    var evtobj=window.event? event : e 
    if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey) 
     alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys") 
} 
document.onkeypress=detectspecialkeys 
7

Utilizzare onkeydown anziché onkeypress può essere d'aiuto.

Da http://www.w3schools.com/jsref/event_onkeypress.asp

Nota: L'evento onkeypress non viene generato per tutti i tasti (ad esempio ALT, CTRL, SHIFT , ESC) in tutti i browser. Per rilevare solo se l'utente ha premuto una chiave, utilizzare invece l'evento onkeydown, perché funziona per tutte le chiavi.

Problemi correlati