KeyboardEvent.code
property represents a physical key on the keyboard (as opposed to the character generated by pressing the key). In other words, this property returns a value that isn't altered by keyboard layout or the state of the modifier keys.
If the input device isn't a physical keyboard, but is instead a virtual keyboard or accessibility device, the returned value will be set by the browser to match as closely as possible to what would happen with a physical keyboard, to maximize compatibility between physical and virtual input devices.
This property is useful when you want to handle keys based on their physical positions on the input device rather than the characters associated with those keys; this is especially common when writing code to handle input for games that simulate a gamepad-like environment using keys on the keyboard. Be aware, however, that you can't use the value reported by
KeyboardEvent.code
to determine the character generated by the keystroke, because the keycode's name may not match the actual character that's printed on the key or that's generated by the computer when the key is pressed.
例如,
code
returned is "
KeyQ
" for the
Q
key on a QWERTY layout keyboard, but the same
code
value also represents the
'
key on Dvorak keyboards and the
A
key on AZERTY keyboards. That makes it impossible to use the value of
code
to determine what the name of the key is to users if they're not using an anticipated keyboard layout.
To determine what character corresponds with the key event, use the
KeyboardEvent.key
特性代替。
The code values for Windows, Linux, and macOS are list on the KeyboardEvent: code values 页面。
<p>Press keys on the keyboard to see what the KeyboardEvent's key and code values are for each one.</p> <div id="output"> </div>
#output {
font-family: Arial, Helvetica, sans-serif;
border: 1px solid black;
}
window.addEventListener("keydown", function(event) {
let str = "KeyboardEvent: key='" + event.key + "' | code='" +
event.code + "'";
let el = document.createElement("span");
el.innerHTML = str + "<br/>";
document.getElementById("output").appendChild(el);
}, true);
To ensure that keystrokes go to the sample, click in the output box below before pressing keys.
This example establishes an event listener for
keydown
events that handle keyboard input for a game that uses the typical "WASD" keyboard layout for steering forward, left, backward, and right. This will use the same four keys physically regardless of what the actual corresponding characters are, such as if the user is using an AZERTY keyboard.
<p>Use the WASD (ZQSD on AZERTY) keys to move and steer.</p> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="world"> <polygon id="spaceship" points="15,0 0,30 30,30"/> </svg> <script>refresh();</script>
.world {
margin: 0px;
padding: 0px;
background-color: black;
width: 400px;
height: 400px;
}
#spaceship {
fill: orange;
stroke: red;
stroke-width: 2px;
}
The first section of the JavaScript code establishes some variables we'll be using.
shipSize
contains the size of the ship the player is moving around, for convenience.
位置
is used to track the position of the ship within the play field.
moveRate
and
turnRate
are the number of pixels forward and backward each keystroke moves the ship and how many degrees of rotation the left and right steering controls apply per keystroke. angle is the current amount of rotation applied to the ship, in degrees; it starts at 0° (pointing straight up). Finally,
spaceship
is set to refer to the element with the ID
"spaceship"
, which is the SVG polygon representing the ship the player controls.
let shipSize = {
width: 30,
height: 30
};
let position = {
x: 200,
y: 200
};
let moveRate = 9;
let turnRate = 5;
let angle = 0;
let spaceship = document.getElementById("spaceship");
Next comes the function
updatePosition()
. This function takes as input the distance the ship is to be moved, where positive is a forward movement and negative is a backward movement. This function computes the new position of the ship given the distance moved and the current direction the ship is facing. It also handles ensuring that the ship wraps across the boundaries of the play field instead of vanishing.
function updatePosition(offset) {
let rad = angle * (Math.PI/180);
position.x += (Math.sin(rad) * offset);
position.y -= (Math.cos(rad) * offset);
if (position.x < 0) {
position.x = 399;
} else if (position.x > 399) {
position.x = 0;
}
if (position.y < 0) {
position.y = 399;
} else if (position.y > 399) {
position.y = 0;
}
}
refresh()
function handles applying the rotation and position by using an
SVG transform
.
function refresh() {
let x = position.x - (shipSize.width/2);
let y = position.y - (shipSize.height/2);
let transform = "translate(" + x + " " + y + ") rotate(" + angle + " 15 15) ";
spaceship.setAttribute("transform", transform);
}
最后,
addEventListener()
method is used to start listening for
keydown
events, acting on each key by updating the ship position and rotation angle, then calling
refresh()
to draw the ship at its new position and angle.
window.addEventListener("keydown", function(event) {
if (event.defaultPrevented) {
return; // Do nothing if event already handled
}
switch(event.code) {
case "KeyS":
case "ArrowDown":
// Handle "back"
updatePosition(-moveRate);
break;
case "KeyW":
case "ArrowUp":
// Handle "forward"
updatePosition(moveRate);
break;
case "KeyA":
case "ArrowLeft":
// Handle "turn left"
angle -= turnRate;
break;
case "KeyD":
case "ArrowRight":
// Handle "turn right"
angle += turnRate;
break;
}
refresh();
// Consume the event so it doesn't get handled twice
event.preventDefault();
}, true);
To ensure that keystrokes go to the sample code, click inside the black game play field below before pressing keys.
There are several ways this code can be made better. Most real games would watch for
keydown
events, start motion when that happens, and stop the motion when the corresponding
keyup
occurs, instead of relying on key repeats. That would allow both smoother and faster movement, but would also allow the player to be moving and steering at the same time. Transitions or animations could be used to make the ship's movement smoother, too.
| 规范 | 状态 | 注释 |
|---|---|---|
|
UI Events
The definition of 'KeyboardEvent.code' in that specification. |
工作草案 | Initial definition, included code values . |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
code
|
Chrome 48 | Edge 79 | Firefox 38 | IE No | Opera 35 | Safari 10 | WebView Android 48 | Chrome Android 48 | Firefox Android 38 | Opera Android 35 | Safari iOS 10 | Samsung Internet Android 5.0 |
完整支持
不支持