如何在onkeydown事件处理程序方法中区分大写字母和较低的大写字母 [英] How to differentiate capital letters from lower ones in onkeydown event handler method
问题描述
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function showChar(e) {
if (e.keyCode != 16) {
alert(
"keyCode: " + e.keyCode + "\n"
+ "SHIFT key pressed: " + e.shiftKey + "\n"
);
}
}
</script>
</head>
<body onkeydown="showChar(event);">
<p>Press any character key, with or without holding down
the SHIFT key.<br /></p>
</body>
</html>
如何区分资本 A 与小写 a 在onkeydown事件处理程序方法?以上算法触发相同的keyCode值。我需要在按下onkeydown时检测大写字母。
How can I differentiate capital A from lowercase a in onkeydown event handler method? Above algorithm fires the same keyCode value. I need to detect the capital letters when they are pressed in onkeydown.
注意:代码包含SHIFT键的例外。否则它不允许输入大写字母。顺便说一句,我需要使用onkeydown进行试用。
Note: The code contains an exception for SHIFT key. Otherwise it does not allow to type capital letters. BTW, I need to use onkeydown for my trial.
推荐答案
在我看来你回答了自己的问题。如果您检测到SHIFT键,则可以轻松区分大写和小写:
It looks to me like you answered your own question. If you are detecting the SHIFT key, you can easily differentiate between capital and lowercase:
if(e.shiftKey){
alert("You pressed a CAPITAL letter with the code " + e.keyCode);
}else{
alert("You pressed a LOWERCASE letter with the code " + e.keyCode);
}
或者我误解了你的问题?
Or am I misunderstanding your question?
更新:大写ASCII代码可以通过添加32轻松转换为小写ASCII代码,所以您需要做的就是:
Update: Upper case ASCII codes can easily be converted to lower case ASCII codes by adding 32, so all you need to do is this:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function showChar(e){
if(e.keyCode!=16){ // If the pressed key is anything other than SHIFT
if(e.keyCode >= 65 && e.keyCode <= 90){ // If the key is a letter
if(e.shiftKey){ // If the SHIFT key is down, return the ASCII code for the capital letter
alert("ASCII Code: "+e.keyCode);
}else{ // If the SHIFT key is not down, convert to the ASCII code for the lowecase letter
alert("ASCII Code: "+(e.keyCode+32));
}
}else{
alert("ASCII Code (non-letter): "+e.keyCode);
}
}
}
</script>
</head>
<body onkeydown="showChar(event);">
<p>Press any character key, with or without holding down
the SHIFT key.<br /></p>
</body>
</html>
更新2:试试这个:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function showChar(e){
if(e.keyCode!=16){ // If the pressed key is anything other than SHIFT
c = String.fromCharCode(e.keyCode);
if(e.shiftKey){ // If the SHIFT key is down, return the ASCII code for the capital letter
alert("ASCII Code: "+e.keyCode+" Character: "+c);
}else{ // If the SHIFT key is not down, convert to the ASCII code for the lowecase letter
c = c.toLowerCase(c);
alert("ASCII Code: "+c.charCodeAt(0)+" Character: "+c);
}
}
}
</script>
</head>
<body onkeydown="showChar(event);">
<p>Press any character key, with or without holding down
the SHIFT key.<br /></p>
</body>
</html>
这篇关于如何在onkeydown事件处理程序方法中区分大写字母和较低的大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!