2010-02-08 9 views

risposta

84

Per l'immissione di caratteri, si consiglia di utilizzare keypress(), che riporta il codice ASCII effettivo per il carattere premuto. Si occupa automaticamente di lettere maiuscole e ignora le pressioni non carattere. In entrambi i casi, è possibile utilizzare fromCharCode() per convertire in una rappresentazione di stringa. Per esempio.

var c = String.fromCharCode(e.which) // or e.keyCode 

Basta ricordare che per keydown() e keyup(), dovrete tenere traccia del caso utilizzando lo stato e.shiftKey.

+5

non funziona per me in Firefox. Ottengo 1/4 quando premo, –

+1

haha ​​.. per qualche motivo, i browser restituiscono 188 quando si preme la virgola, ma quando convertiamo 188 in char, viene come ¼. È interessante notare che quando convertiamo 44 in char, i browser lo capiscono come virgola !! –

+0

Credo che restituisca 1/4 nella vecchia versione di jQuery. In 1.4.2 è stato risolto. Restituisce la virgola per me –

99

L'evento keyPress è ciò di cui hai bisogno per ottenere il carattere inserito. (Vedere la soluzione alternativa per l'evento keydown).

keydown e keyup forniscono un codice che indica quale tasto viene premuto, mentre keypress indica quale carattere è stato inserito.

utilizzando jQuery e.which è possibile ottenere il codice della chiave e l'utilizzo di String.fromCharCode è possibile ottenere il carattere specifico che è stato premuto (compresi shiftKey).

DEMO:http://jsfiddle.net/9TyzP/3

Codice:

element.on ('keypress', function (e) { 
    console.log(String.fromCharCode(e.which)); 
}) 

Nota ho detto e.which perché diversi browser di jQuery utilizzano differenti oggetti da archiviare queste informazioni. jQuery normalizza la proprietà .which in modo che sia possibile utilizzarla in modo affidabile per recuperare il codice chiave.

Soluzione per keydown

Tuttavia è possibile scrivere una semplice soluzione per ottenere il carattere premuto lavorare su keydown .. La soluzione consiste nel creare un oggetto con chiave come il charCode senza spostamento di pressione di un tasto e il valore è con il tasto Maiusc.

Nota: come indicato da @Sajjan Sarkar, ci sono alcune differenze nel valore del codice tasto e.which restituito da un altro browser. Read more here

Aggiornamento del codice DEMO per normalizzare il valore keyCode del browser incrociato. Testato e verificato in IE 8, FF e Chrome.

codice completo DEMO qui sotto e aggiornato:http://jsfiddle.net/S2dyB/17/

$(function() { 

    var _to_ascii = { 
     '188': '44', 
     '109': '45', 
     '190': '46', 
     '191': '47', 
     '192': '96', 
     '220': '92', 
     '222': '39', 
     '221': '93', 
     '219': '91', 
     '173': '45', 
     '187': '61', //IE Key codes 
     '186': '59', //IE Key codes 
     '189': '45' //IE Key codes 
    } 

    var shiftUps = { 
     "96": "~", 
     "49": "!", 
     "50": "@", 
     "51": "#", 
     "52": "$", 
     "53": "%", 
     "54": "^", 
     "55": "&", 
     "56": "*", 
     "57": "(", 
     "48": ")", 
     "45": "_", 
     "61": "+", 
     "91": "{", 
     "93": "}", 
     "92": "|", 
     "59": ":", 
     "39": "\"", 
     "44": "<", 
     "46": ">", 
     "47": "?" 
    }; 

    $(element).on('keydown', function(e) { 
     var c = e.which; 

     //normalize keyCode 
     if (_to_ascii.hasOwnProperty(c)) { 
      c = _to_ascii[c]; 
     } 

     if (!e.shiftKey && (c >= 65 && c <= 90)) { 
      c = String.fromCharCode(c + 32); 
     } else if (e.shiftKey && shiftUps.hasOwnProperty(c)) { 
      //get shifted keyCode value 
      c = shiftUps[c]; 
     } else { 
      c = String.fromCharCode(c); 
     } 

     //$(element).val(c); 
    }).on('keypress', function(e) { 
     //$(element).val(String.fromCharCode(e.which)); 
    });  
}); 

più su eventi di tastiera -

Il KeyDown, pressione del tasto ed eventi keyup fuoco quando l'utente preme un tasto.

keydown Si accende quando l'utente preme un tasto. Si ripete mentre l'utente tiene premuto il tasto.

tasto pressione Si attiva quando un carattere reale viene inserito, ad esempio, in un input di testo. Si ripete mentre l'utente tiene premuto il tasto.

keyup Si attiva quando l'utente rilascia una chiave, dopo che è stata eseguita l'azione predefinita di tale chiave.

Quando si preme per la prima volta un tasto, viene inviato l'evento keydown. Se la chiave non è un tasto di modifica, viene inviato l'evento keypress. Quando l'utente rilascia la chiave, viene inviato l'evento keyup.

Quando si preme e si tiene premuto un tasto, inizia la ripetizione automatica. Ciò si traduce in una sequenza di eventi simili di seguito essere spedita:

keydown 
keypress 
keydown 
keypress 
<<repeating until the user releases the key>> 
keyup 

DEMO:http://jsfiddle.net/9TyzP/1/

keyup, keydown vs Pressione

keydown e keyup eventi rappresentano tasti premuti o rilasciato, mentre l'evento keypress rappresenta un carattere digitato.

DEMO:http://jsfiddle.net/9TyzP/

Riferimenti:

  1. https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent

  2. http://www.quirksmode.org/dom/events/keys.html

  3. http://unixpapa.com/js/key.html

+1

questa sembra una grande risposta canonica, aspetterà qualche giorno così questo ottiene un un po 'più di esposizione prima dell'assegnazione di –

+0

Sì, ma poiché "l'evento keypress non è coperto da alcuna specifica ufficiale, il comportamento effettivo riscontrato durante l'utilizzo può variare tra browser, versioni di browser e piattaforme." src: http: // api .jquery.com/keypress/ 01,AFAIK, non è possibile ottenere il valore ASCII in keydown, è possibile ottenere solo in keyup o keypress come sottolineato dalla persona sopra. –

+0

@SajjanSarkar Non vero .. Si ottiene il 'keyCode' (e.which) su 'keydown/keyup/keypress'. Se si desidera il carattere ASCII, è possibile utilizzare la funzione' String.fromCharCode'. Non si ottiene il carattere in 'keyup/keypr ess'. –

1

Faccio questo. Ignorerà semplicemente la pressione del tasto se il valore non è un numero. sembra funzionare senza problemi ...

$("input").on("keypress", function(e) { 
     if(!jQuery.isNumeric(String.fromCharCode(e.which))) 
      return false; 
    }); 
1

risposta di Selvakumar Arumugam funziona come un fascino per me ... fino a quando ho test del tastierino numerico.Quindi un aggiornamento minore qui:

$(document).on('keydown', function(e) { 
    var c = e.which; 

    if (_to_ascii.hasOwnProperty(c)) { 
     c = _to_ascii[c]; 
    } 

    if (!e.shiftKey && (c >= 65 && c <= 90)) { 
     c = String.fromCharCode(c + 32); 
    } else if (e.shiftKey && shiftUps.hasOwnProperty(c)) { 
     c = shiftUps[c]; 
    } else if (96 <= c && c <= 105) { 
     c = String.fromCharCode(c - 48); 
    }else { 
     c = String.fromCharCode(c); 
    } 

    $kd.val(c); 
}) 

http://jsfiddle.net/S2dyB/78/

0

ho creato e utilizzare il javascript sopra di classe per la conversione gr di en caratteri. Può essere utilizzato per più lingue. Utilizza JQuery per modificare il valore premuto dall'utente.

var CharMapper = function (selector) { 
    this.getLanguageMapper = function (languageSource, languageTarget) { 
     // Check if the map is already defined. 
     if (typeof langugageCharMap === "undefined") { 
      langugageCharMap = {}; 
     } 
     if (typeof langugageCharMap[languageSource] === "undefined") { 
      langugageCharMap[languageSource] = {}; 
     } 

     // Initialize or get the language mapper. 
     if (typeof langugageCharMap[languageSource][languageTarget] === "undefined") { 
      switch (languageSource) { 
       case "GR": 
        switch (languageTarget) { 
         case "EN": 
          langugageCharMap[languageSource][languageTarget] = { 
           "α": "a", "ά": "a", "β": "b", "γ": "g", "δ": "d", "ε": "e", "έ": "e", "ζ": "z", "η": "h", "ή": "h", "θ": "th", "ι": "i", "ί": "i", "ϊ": "i", "ΐ": "i", "κ": "k", "λ": "l", "μ": "m", "ν": "n", "ξ": "ks", "ο": "o", "ό": "o", "π": "p", "ρ": "r", "σ": "s", "ς": "s", "τ": "t", "υ": "y", "ύ": "y", "ϋ": "y", "ΰ": "y", "φ": "f", "χ": "x", "ψ": "ps", "ω": "o", "ώ": "o", "Α": "A", "Ά": "A", "Β": "B", "Γ": "G", "Δ": "D", "Ε": "E", "Έ": "E", "Ζ": "Z", "Η": "H", "Ή": "H", "Θ": "TH", "Ι": "I", "Ί": "I", "Ϊ": "I", "Κ": "K", "Λ": "L", "Μ": "M", "Ν": "N", "Ξ": "KS", "Ο": "O", "Ό": "O", "Π": "P", "Ρ": "R", "Σ": "S", "Τ": "T", "Υ": "Y", "Ύ": "Y", "Ϋ": "Y", "Φ": "F", "Χ": "X", "Ψ": "PS", "Ω": "O", "Ώ": "O" 
          }; 
          break; 
         case "GR": 
         default: 
          throw "Language(" + languageTarget + ") is not supported as target for Language(" + languageSource + ")."; 
        } 
        break; 
       case "EN": 
       default: 
        throw "Language(" + languageSource + ") is not supported as source."; 
      } 
     } 

     return langugageCharMap[languageSource][languageTarget]; 
    }; 
    // Check the existance of the attribute. 
    var items = $(selector).find("*[data-mapkey]"); 
    if (items.length === 0) { 
     return; 
    } 

    // For each item. 
    for (var i = 0; i < items.length; i++) { 
     var item = items[i]; 

     // Get the source and target language. 
     var languages = $(item).attr("data-mapkey"); 
     var languageSource = languages.split("_")[0]; 
     var languageTarget = languages.split("_")[1]; 

     // Add the event listener. 
     var self = this; 
     $(item).keypress(function (event) { 
      event.stopPropagation(); 
      // Get the mapper to use. 
      var mapper = self.getLanguageMapper(languageSource, languageTarget); 
      // Get the key pressed. 
      var keyPressed = String.fromCharCode(event.which); 
      // Get the key to set. In case it doesn't exist in the mapper, get the key pressed. 
      var keyToSet = mapper[keyPressed] || keyPressed; 
      // Set the key to the dom. 
      this.value = this.value + keyToSet; 

      // Do not propagate. 
      return false; 
     }); 
    } 
}; 

Esempio,

<input type="text" data-mapkey="GR_EN" /> 
<script type="text/javascript"> 
    new CharMapper("body"); 
</script>