onkeydown and onkeyup events don't work on Internet Explorer 8

拈花ヽ惹草 提交于 2019-12-07 12:24:36

问题


My code works without problems on IE9/IE10, FF, Chrome and opera but on older Internet Explorer no Keyboard input is handled.

I have the following code for handling events. It should only fire when a new button is pressed.

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];
};

回答1:


Try

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];
};



回答2:


You need to bind to the document, not window.

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

needs to be

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



回答3:


You have to use normalized key code. Like this:

var keyCode = event.which || event.keyCode;



回答4:


I tried different solutions but these still did not work correctly in IE8. What I came up with that worked is this:

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
}


来源:https://stackoverflow.com/questions/16399150/onkeydown-and-onkeyup-events-dont-work-on-internet-explorer-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!