onKeyPress event not working in Firefox

后端 未结 4 1792
闹比i
闹比i 2020-12-01 18:58

I have the following javascript code...Here I am using onKeyPress=\"someFunction( )\" in the body tag to get the keyCode of the key that is pressed.

相关标签:
4条回答
  • 2020-12-01 19:43

    I think Firefox are not caring programmers... and this is the reason why so, In Firefox navigator.appName returns "Netscape". so user can edit his code like,

    if(navigator.appName == "Netscape") 
        Key = event.charCode; //or e.which; (standard method)
    else 
        Key = event.keyCode;
    
    0 讨论(0)
  • 2020-12-01 19:47

    Browsers have different ways of handling keyboard events. Have a look at http://unixpapa.com/js/key.html for more info.

    For example, these changes to your code will get it working in Firefox:

    <body bgcolor="lightblue" onkeypress="keypress(e)">
    

    and

    function keypress(e) {
        alert(window.event ? event.keyCode : e.which);
        // other stuff
    }
    
    0 讨论(0)
  • 2020-12-01 19:48

    Pass event object as an parameter and your code will work in IE as well as firefox. The code example is as follows :

    <body bgcolor="lightblue" onkeypress="keypress(event)">
    
    function keypress(event) {
      alert(event.keyCode);
      var key=event.keyCode;
      if(key==112 || key==80)
          printDiv();
      else if(key==101 || key==69)
          window.location="http://google.com";
      else if(key==114 || key==82)
          window.reset();  
    }
    
    0 讨论(0)
  • 2020-12-01 19:54

    When problems like this show up, I start to use any kind of a JavaScript framework. Those frameworks are build to avoid problems with different browsers.

    To catch all different keypress() apis, like the link from Emmett shows, can be very difficult.

    Example:

    In HTML head:

    <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
    

    In the JS tag:

    $(document).keydown(function(event) {
     alert('You pressed '+event.keyCode);
     event.preventDefault();
    });
    
    0 讨论(0)
提交回复
热议问题