javascript onkeydown的问题-event.仅给出大写字符 [英] Issue with javascript onkeydown - event.which give characters in upper case only

查看:48
本文介绍了javascript onkeydown的问题-event.仅给出大写字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一段JavaScript代码来在文本区域内按下键.我使用了onkeydown事件来捕获按下的键,并在事件触发时调用一个函数.在函数中,我正在使用event.which来按下键.但这并不能提供正确的按键.对于任何按下的字符,它都会给出相应的大写字符的Ascii值(仅65到90).即使输入了小写字符,它也不给出小写字符的Ascii值,即97到122.例如-如果我输入'a',则其Ascii值为'A'有谁知道为什么会这样吗?这是我正在使用的代码-

I have written a piece of javascript code to get the key pressed within a text area. I have used the onkeydown event to capture the key pressed and am calling a function when the event is triggered. Within the function i am using event.which to get the key pressed. But this is not giving the correct key pressed. For any character pressed, it gives the Ascii value of the corresponding upper case character ( 65 to 90 only ). It is not giving Ascii values for the lower case characters, ie 97 to 122, even if a lower case character has been typed. Eg - If i type 'a' it gives the Ascii value of 'A' Does any one know why this is happening ? Here is the code i am using -

var mainDoc = document.getElementById("mainDoc");
mainDoc.onkeydown = function(event){keyPress(event);}
function keyPress(event)
{
    alert("key code : "+ event.which + " );
}

我尝试使用onkeypress事件.这似乎可以正常工作,但不能捕获alt,control,箭头键等.

I tried using onkeypress event. This seems to work fine, but it does not capture the alt, control, arrow keys etc.

推荐答案

keydown keyup (基本上)根本不会给您提供字符 ,它们会为您提供键码. keypress 是获取字符的位置(并且,如果需要知道的话,还可以输入事件对象的 ctrlKey 上的修改键的状态,即键入该字符时的状态, altKey shiftKey metaKey 属性).此页面详细介绍了JavaScript中的键盘事件.

keydown and keyup don't (mostly) give you characters at all, they give you keycodes. keypress is where you get characters (and if you need to know, also the state of the modifier keys as of when that character was typed, on the event object's ctrlKey, altKey, shiftKey, and metaKey properties). This page goes into the madness that is keyboard events in JavaScript in loving detail...

这篇关于javascript onkeydown的问题-event.仅给出大写字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆