How to register document.onkeypress event

不打扰是莪最后的温柔 提交于 2019-12-17 15:38:26

问题


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

I have used:

document.attachEvent("onkeydown", my_onkeydown_handler);

It works fine with IE, but not with Firefox and 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.

Is there a solution, am I missing something?


回答1:


You are looking for:

EDIT:

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




回答2:


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.




回答3:


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

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.
}


来源:https://stackoverflow.com/questions/12153357/how-to-register-document-onkeypress-event

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