如何在 JavaScript 中找出按下了哪个字符键?
javascriptweb developmentobject oriented programming更新于 2025/10/30 5:32:17
要找出按下了哪个字符键,请使用 window.event 和 keyCode。以下是代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=
1.0">
<title>Document</title>
<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>
</head>
<body>
<form>
<input type="text" onkeypress="return keyPressName(event)" />
</form>
<script>
function keyPressName(myEventKeyName){
var pressedKey;
if(window.event){
pressedKey = myEventKeyName.keyCode;
} else if(myEventKeyName.which)
{
pressedKey = myEventKeyName.which;
}
alert(String.fromCharCode(pressedKey));
}
</script>
</body>
</html>
要运行上述程序,请将文件名保存为"anyName.html(index.html)",然后右键单击该文件。在 VS Code 编辑器中选择选项"使用 Live Server 打开"。
输出
将产生以下输出 −

在这里,我按下了字符 g。这将产生以下输出 −

显示字符 g 后,单击"确定"按钮,您将获得以下输出。

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

