1

我已将此功能附加到使用 jquery 的按键事件中,但在 eventObject 中,它为输入的大写和小写字符返回相同的字符代码

function keyPressed(delegates,eventdata){
        var keyType = new KeyType();
        var keycode = eventdata.which;
        if((keycode === 0)&&(eventdata.keyCode === 46)){
            keycode=46;
        }
        switch(keycode)
        {
        case keyType.enter:
            break;
        case keyType.backspace:
            break;
        case keyType.del:
            break;
        case keyType.space:
            break;
        default:
            keycode = 1;
        }
        console.log(eventdata.charCode);
        console.log(eventdata.which);
        console.log(eventdata.keyCode);
        //if a delegate is present call it
        var delegate = delegates[keycode];
        if(delegate !== null){
            delegate(eventdata);
    }
}
4

2 回答 2

1

字符代码表示按下的键。您的键盘只有一个键用于“a”和“A”。您还需要检查 shift 键:

  if (eventData.shiftKey) {
    //Shift
  }
  if (eventData.ctrlKey) {
    //Ctrl
  }
  if (eventData.altKey) {
    //Alt
  }
于 2012-07-22T01:10:37.983 回答
1

当使用 jQuery 检测键盘/鼠标事件时,您应该始终使用event.which来获取规范化的用户跨浏览器输入。

Slightly off-topic illustrative history, couple months ago I made an userscript in Vanilla JS which runs perfectly fine in FF and Chrome, and just now I had a report that it wasn't working in Opera. I quickly debugged it on Opera and of course, the event.keyCode was returning 0 when it should be the key's value.

So yes, whenever you can use jQuery's event.which to handle user-input, use it to save a lot of headaches.

keydown and keypress are different events and as such may report different values for different events -- which may differ further into having a keyCode and/or charCode properties in different browsers. event.which minimizes those discrepancies.

于 2012-07-22T04:50:42.673 回答