我需要在keypress
事件上获取本地化字符。例如:在捷克语键盘上,我需要获得非5个字符(键码53)(请参阅Czech keyboard layout)。还有其他获取字符且不使用文本输入和读取值的方法吗?换句话说,有什么方法可以从事件对象中获取符合当前用户键盘布局的字符?
(添加了示例代码)
<html>
<body>
<script language="JavaScript">
function onLoad() {
console.log(document.getElementById("test"));
document.getElementById("test").onkeydown = function(event) {
console.log("Code: "+event.keyCode+"; Key: "+String.fromCharCode(event.keyCode));
}
}
</script>
<body onLoad="onLoad();">
<input id="test">
</body>
</html>
(示例online)
尝试使用此代码并按ř键时,您将在Firebug控制台中看到“代码:53;键:5”。我需要得到“ř”而不是“5”。
我认为这个“问题”出现在所有非英语键盘上。
最佳答案
无论键盘布局如何,使用keypress
事件都会为您键入字符。
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charTyped = String.fromCharCode(charCode);
alert("Character typed: " + charTyped);
};
这是我通常链接到Jan Wolter出色的页面的页面,该页面记录了JavaScript key 处理:http://unixpapa.com/js/key.html