JS Reference

JS by Category JS by Alphabet

JavaScript

JS Array JS Boolean JS Classes JS Date JS Error JS Global JS JSON JS Math JS Number JS Operators JS RegExp JS Statements JS String

Window

Window Object Window Console Window History Window Location Window Navigator Window Screen

HTML DOM

DOM Document DOM Element DOM Attributes DOM Events DOM Event Objects DOM HTMLCollection DOM Style
alignContent alignItems alignSelf animation animationDelay animationDirection animationDuration animationFillMode animationIterationCount animationName animationTimingFunction animationPlayState background backgroundAttachment backgroundColor backgroundImage backgroundPosition backgroundRepeat backgroundClip backgroundOrigin backgroundSize backfaceVisibility border borderBottom borderBottomColor borderBottomLeftRadius borderBottomRightRadius borderBottomStyle borderBottomWidth borderCollapse borderColor borderImage borderImageOutset borderImageRepeat borderImageSlice borderImageSource borderImageWidth borderLeft borderLeftColor borderLeftStyle borderLeftWidth borderRadius borderRight borderRightColor borderRightStyle borderRightWidth borderSpacing borderStyle borderTop borderTopColor borderTopLeftRadius borderTopRightRadius borderTopStyle borderTopWidth borderWidth bottom boxShadow boxSizing captionSide caretColor clear clip color columnCount columnFill columnGap columnRule columnRuleColor columnRuleStyle columnRuleWidth columns columnSpan columnWidth counterIncrement counterReset cursor direction display emptyCells filter flex flexBasis flexDirection flexFlow flexGrow flexShrink flexWrap cssFloat font fontFamily fontSize fontStyle fontVariant fontWeight fontSizeAdjust height isolation justifyContent left letterSpacing lineHeight listStyle listStyleImage listStylePosition listStyleType margin marginBottom marginLeft marginRight marginTop maxHeight maxWidth minHeight minWidth objectFit objectPosition opacity order orphans outline outlineColor outlineOffset outlineStyle outlineWidth overflow overflowX overflowY padding paddingBottom paddingLeft paddingRight paddingTop pageBreakAfter pageBreakBefore pageBreakInside perspective perspectiveOrigin position quotes resize right scrollBehavior tableLayout tabSize textAlign textAlignLast textDecoration textDecorationColor textDecorationLine textDecorationStyle textIndent textOverflow textShadow textTransform top transform transformOrigin transformStyle transition transitionProperty transitionDuration transitionTimingFunction transitionDelay unicodeBidi userSelect verticalAlign visibility width wordBreak wordSpacing wordWrap widows zIndex

Web APIs

API Console API Fullscreen API Geolocation API History API MediaQueryList API Storage

HTML Objects

<a> <abbr> <address> <area> <article> <aside> <audio> <b> <base> <bdo> <blockquote> <body> <br> <button> <canvas> <caption> <cite> <code> <col> <colgroup> <datalist> <dd> <del> <details> <dfn> <dialog> <div> <dl> <dt> <em> <embed> <fieldset> <figcaption> <figure> <footer> <form> <head> <header> <h1> - <h6> <hr> <html> <i> <iframe> <img> <ins> <input> button <input> checkbox <input> color <input> date <input> datetime <input> datetime-local <input> email <input> file <input> hidden <input> image <input> month <input> number <input> password <input> radio <input> range <input> reset <input> search <input> submit <input> text <input> time <input> url <input> week <kbd> <label> <legend> <li> <link> <map> <mark> <menu> <menuitem> <meta> <meter> <nav> <object> <ol> <optgroup> <option> <output> <p> <param> <pre> <progress> <q> <s> <samp> <script> <section> <select> <small> <source> <span> <strong> <style> <sub> <summary> <sup> <table> <tbody> <td> <tfoot> <th> <thead> <tr> <textarea> <time> <title> <track> <u> <ul> <var> <video>

Other References

CSSStyleDeclaration JS Conversion


KeyboardEvent quale proprietà

Esempio

Ottieni il valore Unicode del tasto della tastiera premuto:

var x = event.which;

Altri esempi "Provalo da solo" di seguito.


Definizione e utilizzo

La proprietà which restituisce il codice carattere Unicode della chiave che ha attivato l' evento onkeypress o il codice chiave Unicode della chiave che ha attivato l' evento onkeydown o onkeyup .

La differenza tra i due tipi di codice:

  • Codici carattere: un numero che rappresenta un carattere ASCII
  • Codici tasti - Un numero che rappresenta un tasto effettivo sulla tastiera

Questi tipi non significano sempre la stessa cosa; ad esempio, una "w" minuscola e una "W" maiuscola hanno lo stesso codice della tastiera, perché il tasto che viene premuto sulla tastiera è lo stesso (solo "W" = il numero "87"), ma un diverso codice carattere perché il carattere risultante è diverso (o "w" o "W", che è "119" o "87") - Vedi "Altri esempi" di seguito per capirlo meglio.

Suggerimento: per sapere se l'utente sta premendo un tasto stampabile (ad es. "a" o "5"), si consiglia di utilizzare questa proprietà sull'evento onkeypress. Per scoprire se l'utente sta premendo un tasto funzione (es. "F1", "BLOC MAIUSC" o "Home") utilizzare l'evento onkeydown o onkeyup.

Nota: la proprietà which non è supportata in IE8 e versioni precedenti. Per queste versioni del browser, puoi utilizzare la proprietà keyCode . Tuttavia, la proprietà keyCode non funziona sull'evento onkeypress in Firefox. Per una soluzione cross-browser, puoi utilizzare il codice seguente:

var x = event.which || event.keyCode;  // Use either which or keyCode, depending on browser support

Suggerimento: per un elenco di tutti i caratteri Unicode, consulta il nostro Riferimento Unicode completo .

Suggerimento: se desideri convertire il valore Unicode restituito in un carattere, utilizza il metodo fromCharCode() .

Nota: questa proprietà è di sola lettura.

Nota: sia la proprietà which che quella keyCode sono fornite solo per la compatibilità. L'ultima versione della specifica degli eventi DOM consiglia di utilizzare invece la proprietà chiave (se disponibile).

Suggerimento: se vuoi scoprire se il tasto "ALT", "CTRL", "META" o "SHIFT" è stato premuto quando si è verificato un evento chiave, usa la proprietà altKey , ctrlKey , metaKey o shiftKey .


Supporto browser

I numeri nella tabella specificano la prima versione del browser che supporta completamente la proprietà.

Property
which Yes 9.0 Yes Yes Yes


Sintassi

event.which

Dettagli tecnici

Valore di ritorno: Un numero, che rappresenta un codice carattere Unicode o il codice chiave Unicode
Versione DOM: Eventi DOM di livello 2

Altri esempi

Esempio

Utilizzo di onkeypress e onkeydown per dimostrare le differenze tra codici carattere e codici tastiera:

<input type="text" onkeypress="uniCharCode(event)" onkeydown="uniKeyCode(event)">

function uniCharCode(event) {
  var char = event.which || event.keyCode; // event.keyCode is used for IE8 and earlier
  document.getElementById("demo").innerHTML = "Unicode CHARACTER code: " + char;
}

function uniKeyCode(event) {
  var key = event.which || event.keyCode; // event.keyCode is used for IE8 and earlier
  document.getElementById("demo2").innerHTML = "Unicode KEY code: " + key;
}

Quando si preme il tasto "a" sulla tastiera (non si utilizza il blocco maiuscole), il risultato di char e key sarà:

Unicode CHARACTER code: 97
Unicode KEY code: 65

Esempio

Avvisa del testo se l'utente preme il tasto Esc:

<input type="text" onkeydown="myFunction(event)">

function myFunction(event) {
  var x = event.which || event.keyCode; // event.keyCode is used for IE8 and earlier
  if (x == 27) {  // 27 is the ESC key
    alert ("You pressed the Escape key!");
  }
}

Esempio

Converti il ​​valore Unicode in un carattere (non funziona per i tasti funzione):

var x = event.which || event.keyCode;   // Get the Unicode value
var y = String.fromCharCode(x);         // Convert the value into a character

Pagine correlate

Riferimento HTML DOM: chiave KeyboardEvent Property

Riferimento HTML DOM: KeyboardEvent keyCode Property

Riferimento HTML DOM: proprietà KeyboardEvent charCode