Key code check in Javascript not working for IE

前端 未结 2 665
感情败类
感情败类 2021-01-25 17:59

I tired to write a function to check key code with javascript. It\'s working fine for firefox but not IE. Does anyone know what is going wrong with my code? Please see below cod

相关标签:
2条回答
  • 2021-01-25 18:29

    keyCode and charCode values behave slightly differently in different browsers and return different values for various events. Older versions of IE in particular don't support charCode. The first suggestion I have is to use a tool like jQuery to handle normalization of the key values across browsers. With jQuery you can use the e.which property on the event object to get the normalized value.

    The other thing to do is use a key code checker to compare the values returned for each event for each browser. I built a handy online tool to do this and found it extremely useful to show all the keycodes/charcodes for each of the events at a glance:

    http://www.west-wind.com/WestwindWebToolkit/samples/Ajax/html5andCss3/keycodechecker.aspx

    Makes it real easy to experiment with different key combinations and see how they compare on different browsers. jQuery's which and keypress tend to be the one that works most consistently.

    0 讨论(0)
  • 2021-01-25 18:43

    switch your first line of code:

    ...

    var e = e || window.event;
    

    ...

    and see if that helps.

    Also, if it is a unicode character try something like the following:

    function displayunicode(e) {
        var unicode=e.keyCode? e.keyCode : e.charCode
        alert(unicode)
    }
    

    If you're handling keydown instead of keypress, then things get a bit more complex... See: http://unixpapa.com/js/key.html

    0 讨论(0)
提交回复
热议问题