JavaScript - Detect ESC key cross browser [duplicate]
Possible Duplicate:
Which keycode for escape key with jQuery
This little piece of code works like a charm for Firefox and Opera. Internet Explorer doesn't like it.
window.document.onkeydown = function (e) {
if (!e) {
e = event;
}
if (e.keyCode == 27) {
myfunction();
}
}
Isn't it possible to detect keydown for ESC in IE? Thanks
Which version of IE do you have? This code works for me with IE (9.01):
<!doctype html>
<html>
<head>
<title></title>
<script type="text/javascript">
window.document.onkeydown = function (e)
{
if (!e) e = event;
if (e.keyCode == 27)
alert("Hello!");
}
</script>
</head>
<body>
</body>
</html>
Check also your Doctype, your IE could use the Quirks mode, maybe.
Some browsers use e.keyCode, others e.charCode. Also, this varies for the type of event, some browsers (like FF) will use one for one type of key, and the other for another type (such as letters vs. arrow keys)
However, testing this in jsfiddle, it looks like e.keyCode is the right check for IE9. Which version of IE are you testing with?
精彩评论