我正在尝试编写以下脚本,但是有点卡住...。
我也有以下内容:
function convert(){
String.fromCharCode(event.charCode);
}
addEventListener("keypress", convert);
我正在尝试在HTML页面中显示所按下的键以及键的字符代码。
我如何输出上述功能,感谢您的帮助,谢谢!
Keypress has been deprecated;您应该使用keydown
。另外,您需要确保将event
传递给函数。请参见下面的工作示例。
function convert(event){
const char = String.fromCharCode(event.keyCode);
const newLine = document.createElement('P');
newLine.innerHTML = 'You pressed ' + char + ' character code ' + event.keyCode;
document.getElementById('output').appendChild(newLine);
}
document.getElementById("inp").addEventListener("keydown", convert);
<input id="inp" />
<div id="output"></div>