javascript 为什么 keydown 侦听器在 IE 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9507200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:54:53  来源:igfitidea点击:

Why keydown listener doesn't work in IE

javascriptinternet-explorereventsonkeydown

提问by Ixx

Im trying to run this in IE 8 but it doesn't work, any idea? It works in Firefox, Chrome, Opera...

我试图在 IE 8 中运行它,但它不起作用,知道吗?它适用于 Firefox、Chrome、Opera...

preventBackspace();

function preventBackspace() {
    try {
        if (window.addEventListener) {
            window.addEventListener("keydown", onKeyDown, true);
        } else if (window.attachEvent) { // IE 
            alert(window);
            window.attachEvent("onkeydown", onKeyDown);
        } else {
            document.addEventListener("keydown", onKeyDown, true);
        }
        } catch (e) {
            alert(e);
    }
}

function onKeyDown(e) {
    alert("test!");
}

jsfiddle:

jsfiddle:

http://jsfiddle.net/ubfBq/

http://jsfiddle.net/ubfBq/

window.attachEvent is defined and the event listener added. But it never shows "test!" alert.

window.attachEvent 已定义并添加了事件侦听器。但它从不显示“测试!” 警报。

I read something about useCapture flag, which is possible to use in the other methods. It captures the key press on the window before the event "goes down". Internet Explorer doesn't seem to allow/use this. Is that the problem? If yes, how can I solve it?

我读了一些关于 useCapture 标志的内容,它可以在其他方法中使用。它在事件“下降”之前捕获窗口上的按键。Internet Explorer 似乎不允许/使用它。这是问题吗?如果是,我该如何解决?

采纳答案by Snuffleupagus

Use document.attachEvent instead. :]

请改用 document.attachEvent。:]

回答by Jonathan Lonowski

It appears that only IE9 and later support binding keydownon window: http://www.quirksmode.org/dom/events/keys.html#t00

看来,只有IE9及更高版本支持绑定keydownwindowhttp://www.quirksmode.org/dom/events/keys.html#t00

Instead, bind it to the documentfor IE:

相反,将其绑定到documentfor IE:

function preventBackspace() {
    try {
        if (window.addEventListener) {
            window.addEventListener("keydown", onKeyDown, true);
        } else if (document.attachEvent) { // IE 
            alert(document);
            document.attachEvent("onkeydown", onKeyDown);
        } else {
            document.addEventListener("keydown", onKeyDown, true);
        }
    } catch (e) {
        alert(e);
    }
}