3

我的代码在 IE9/IE10、FF、Chrome 和 opera 上运行没有问题,但在较旧的 Internet Explorer 上没有处理键盘输入。

我有以下用于处理事件的代码。它应该只在按下新按钮时触发。

lastEvent = void 0;

heldKeys = {};

window.onkeydown = function(event) {
if (lastEvent && lastEvent.keyCode === event.keyCode) {
  return;
}
lastEvent = event;
heldKeys[event.keyCode] = true;
switch (event.which) {
  case 80:
    return myamp.userInput("positiv");
  case 81:
    return myamp.userInput("negativ");
}
};

window.onkeyup = function(event) {
  lastEvent = null;
  return delete heldKeys[event.keyCode];
};
4

4 回答 4

4

您需要绑定到文档,而不是窗口。

window.onkeyup = function(event) {
window.onkeydown = function(event) {

需要是

document.onkeyup = function(event) {
document.onkeydown = function(event) {
于 2013-05-06T12:57:56.760 回答
1

您必须使用规范化的密钥代码。像这样:

var keyCode = event.which || event.keyCode;
于 2013-05-06T12:57:03.117 回答
1

尝试

lastEvent = void 0;

heldKeys = {};

window.onkeydown = function(event) {
    event = event || window.event; //IE does not pass the event object
    if (lastEvent && lastEvent.keyCode === event.keyCode) {
        return;
    }
    lastEvent = event;
    heldKeys[event.keyCode] = true;

    var keyCode = event.which || event.keyCode; //key property also different

    switch (keyCode) {
        case 80:
            return myamp.userInput("positiv");
        case 81:
            return myamp.userInput("negativ");
    }
};

window.onkeyup = function(event) {
    event = event || window.event;
    lastEvent = null;
    return delete heldKeys[event.keyCode];
};
于 2013-05-06T12:58:02.463 回答
0

我尝试了不同的解决方案,但这些在 IE8 中仍然无法正常工作。我想出的是这样的:

window.onkeyup = function(e) {
    e = (e) ? e : window.event; // check if e is defined
    var kc = (e) ? e.which : e.keyCode; // assign keyCode
    key = (key === undefined) ? e.keyCode : kc; // if keyCode still undefined, reassign it
    if (kc == 13) {
        //enter was pressed
    }
    // other code
}
于 2015-08-16T18:49:49.977 回答