开发者

JavaScript - Detect ESC key cross browser [duplicate]

This question already has answers here: 开发者_开发问答 Closed 11 years ago.

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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜