问题
I have a page where I have to close a dialog when Esc is pressed. I wrote the following simplified code example for this task:
<html>
<head>
<script language="JavaScript">
function keyUpExample() {
alert('on' + event.type + ' event fired by ' + '"' + event.srcElement.id + '" ' + ' ' + event.which)
}
</script>
</head>
<body id="myBody" onkeyup="keyUpExample()">
Trying keyUp event: Press any key...
</body>
</html>
This works as expected under Chrome but is NOT working under IE 7. Is there any workaround on order to cope this problem?
Thanks in advance!
回答1:
Key events don't have to be caught by the body, but document or window works across browsers. Also, keyCode returns the correct value for keyup or down events.
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Small Page</title>
<html>
<head>
<script>
function keyUpExample(e){
e=e || window.event;
var who= e.target || e.srcElement;
alert(e.type+' caught at '+who.nodeName+ ': key #'+e.keyCode)
}
window.onload=function(){
document.onkeyup= keyUpExample;
document.body.onkeyup= keyUpExample;
}
</script>
</head>
<body>
Trying keyUp event: Press any key...
</body>
</html>
回答2:
Pass event as an argument to the callback, and check for window.event for IE.
<html>
<head>
<script>
function keyUpExample(e) {
e = e || window.event;
alert('on' + e.type + ' event fired by ' + '"' + e.srcElement.id + '" ' + ' ' + e.which)
}
</script>
</head>
<body id="myBody" onkeyup="keyUpExample()">
Trying keyUp event: Press any key...
</body>
</html>
Demo
element.onkeyup reference
However
You're better off using a library which smooths out all the ugly cross-browser inconsistencies. Take your pick: jQuery, Prototype, YUI, Dojo, MooTools, RightJS...
回答3:
Are you allowed to use jQuery? If so, then you can accomplish it with .keyup().
Using jQuery also means you can generally leave the cross-browser worries to somebody else.
回答4:
try
function keyUpExample(e) {
var evt = e || event;
alert('on' + evt.type + ' event fired by ' + '"' + ((evt.srcElement)?evt.srcElement.id:evt.target.id) + '" ' + ' ' + ((evt.which)?evt.which:evt.keyCode))
}
回答5:
It is actually very simple, a raw JavaScript solution could look kinda like this
function callback(event) {
if (event.keyCode == 27) {
alert('Here you go!');
}
}
if (document.addEventListener) {
document.addEventListener('keydown', callback, false);
} else {
document.attachEvent('onkeydown', callback);
}
Just attach it to the document no need for any onload trickery.
Also, as people suggested you, check RightJS, it's very lightweight and friendly, and you will be able to do things like those :)
http://rightjs.org/plugins/keys
来源:https://stackoverflow.com/questions/5554765/onkeyup-not-firing-for-esc-in-ie