问题
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