在 JavaScript 中检测按键的最简单方法是什么?
javascriptweb developmentobject oriented programming更新于 2025/10/30 6:04:17
在 JavaScript 中检测按键的最简单方法是使用 onKeyPress 事件处理程序 −
document.onkeypress
按键与 keyCode 属性匹配,该属性返回触发 onkeypress 事件的按键的 Unicode 字符代码。
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=
1.0">
<title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<script>
document.onkeypress = function (eventKeyName) {
eventKeyName = eventKeyName || window.event;
if(eventKeyName.keyCode==13){
console.log('You have pressed enter key');
} else {
alert(String.fromCharCode(eventKeyName.keyCode))
}
};
</script>
</body>
</html>
要运行上述程序,请将文件名保存为"anyName.html(index.html)",然后右键单击该文件。在 VS Code 编辑器中选择选项"使用 Live Server 打开"。
输出
将产生以下输出 −
案例 1− 按下 ENTER 键时,您将在控制台上获得以下输出。

案例 2 − 当您按下除 ENTER 之外的任何其他键(例如字母 g)时,控制台上将显示相同的内容 −

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

