--- title: KeyboardEvent.which slug: Web/API/UIEvent/which tags: - Code - DOM - Key - KeyboardEvent - keyCode - which translation_of: Web/API/KeyboardEvent/which original_slug: Web/API/KeyboardEvent/which ---
{{domxref("KeyboardEvent")}} 接口的 which 只读属性返回所按下键的数字 keyCode 或所按下字母数字键的字符代码 (charCode) 。
var keyResult = event.which;
keyResult contains the numeric code for a particular key pressed, depending on whether an alphanumeric or non-alphanumeric key was pressed. Please see {{domxref("KeyboardEvent.charCode")}} and {{domxref("KeyboardEvent.keyCode")}} for more details.<html>
<head>
<title>charCode/keyCode/which example</title>
<script type="text/javascript">
function showKeyPress(evt) {
alert("onkeypress handler: \n"
+ "keyCode property: " + evt.keyCode + "\n"
+ "which property: " + evt.which + "\n"
+ "charCode property: " + evt.charCode + "\n"
+ "Character Key Pressed: "
+ String.fromCharCode(evt.charCode) + "\n"
);
}
function keyDown(evt) {
alert("onkeydown handler: \n"
+ "keyCode property: " + evt.keyCode + "\n"
+ "which property: " + evt.which + "\n"
);
}
</script>
</head>
<body
onkeypress="showKeyPress(event);"
onkeydown="keyDown(event);"
>
<p>Please press any key.</p>
</body>
</html>
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('DOM3 Events','#legacy-interface-KeyboardEvent','KeyboardEvent.which')}} | {{Spec2('DOM3 Events')}} | Initial definition; specified as deprecated |
{{Compat("api.KeyboardEvent.which")}}