Capturing onkeydown in Javascript

可紊 提交于 2019-12-01 00:29:49

UPDATED

I've sorted this out now. Sorry for removing the context for the comments below, but hey, the previous versions are still there.

It turns out that there are two problems to be fixed in IE: first is that contrary to what I said before, putting an onkeydown attribute in the <body> doesn't work. You need to attach it to the document instead. The second issue is that IE won't let you suppress magic behaviour such as the search dialog triggered by the F3 key unless you do an evil hack involving changing the keydown event's keyCode property, which is clearly a Very Wrong Thing Indeed. Be that as it may, remove the onkeydown attribute in the <body> and the following should do the job (now amended to work in Opera also):

var keyCodeMap = {
    "1013": "EN",
    "1033": "UP",
    "1034": "DN",
    "1112": "01",
    "1113": "02",
    "1114": "03"
    // ...(F4 thru F24 here)...
};

var suppressKeypress = false;

function setCmdKey(e) {
    e = e || window.event;
    var wrkkeyCode = e.keyCode;
    if (wrkkeyCode != 13 &&
        wrkkeyCode != 33 &&
        wrkkeyCode != 34 &&
        wrkkeyCode != 27 &&
        wrkkeyCode < 112) return;

    wrkkeyCode += 1000;

    if (e.shiftKey) wrkkeyCode += 1000;
    var cmdkeycode = keyCodeMap[wrkkeyCode];
    if (!cmdkeycode) return; /* Anything else should be ignored */

    var input = document.forms[0].elements["CmdKey"];
    input.value = "F" + cmdkeycode;
    input.name = "_K" + cmdkeycode;

    try {
        // Prevent default action in IE by bad hacky means
        e.keyCode = 0;
    } catch (ex) {
        // Other browsers do not allow setting the keyCode
    }
    suppressKeypress = true;

    if (ONSUBMITFUN()) document.forms[0].submit();
    return false;
}

document.onkeydown = setCmdKey;
document.onkeypress = function() {
    if (suppressKeypress) {
        return false;
    }
};

You should always return false from event handlers even if you have prevented default by modifying the event, see Quirks mode for more information.

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