onKeyUp not firing for ESC in IE

时光总嘲笑我的痴心妄想 提交于 2019-12-02 04:24:06

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>

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

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.

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

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

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