Javascript 如何注册 document.onkeypress 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12153357/
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-08-23 07:14:51  来源:igfitidea点击:

How to register document.onkeypress event

javascripteventscross-browser

提问by Nilesh Pethani

I want to register keypress events for a document using javascript.

我想使用 javascript 为文档注册按键事件。

I have used:

我用过了:

document.attachEvent("onkeydown", my_onkeydown_handler);

It works fine with IE, but not with Firefox and Chrome.

它适用于 IE,但不适用于 Firefox 和 Chrome。

I also tried:

我也试过:

document.addEventListener("onkeydown", my_onkeydown_handler, true); 
// (with false value also)

But it still doesn't work with Firefox and Chrome.

但它仍然不适用于 Firefox 和 Chrome。

Is there a solution, am I missing something?

有没有解决方案,我错过了什么?

回答by Vishal Suthar

You are looking for:

您正在寻找:

EDIT:

编辑:

Javascript:

Javascript:

document.addEventListener("keydown", keyDownTextField, false);

function keyDownTextField(e) {
var keyCode = e.keyCode;
  if(keyCode==13) {
  alert("You hit the enter key.");
  } else {
  alert("Oh no you didn't.");
  }
}

DEMO: JSFIDDLE

演示: JSFIDDLE

回答by Lucas Green

You are probably looking for:

您可能正在寻找:

document.body.addEventListener('keydown', function (e) {
    alert('hello world');
});???????

But it is almost certainly going to be worth your time to use an existing library to abstract over the problems of the many browsers out there.

但是几乎可以肯定,您花时间使用现有的库来抽象出许多浏览器的问题是值得的。

回答by Kapil Sharma

Please go through following links for detailed description.

请通过以下链接了解详细说明。

https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener?redirectlocale=en-US&redirectslug=DOM%3Aelement.addEventListener

https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener?redirectlocale=en-US&redirectslug=DOM%3Aelement.addEventListener

http://www.reloco.com.ar/mozilla/compat.html

http://www.reloco.com.ar/mozilla/compat.html

In short, write handler as

简而言之,将处理程序写为

function myFunction(e)
{
    ///For IE
    if(!e)
        e=window.event;

    // use e as event in rest of code.
}