keypress event not working in IE and Chrome but working in FF

前端 未结 3 1097
甜味超标
甜味超标 2020-12-10 02:58

Any idea why this might happen? I would usually think that Chrome would be more forgiving with the codes?

$(document).keypress(function(e) {
    if(e.keyCode         


        
3条回答
  •  萌比男神i
    2020-12-10 03:36

    Change keypress to keydown:

    $(document).keydown(function(e) {
        if(e.keyCode == 39) rightImage();
        if(e.keyCode == 37) leftImage();
    });
    

    The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.

    In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

提交回复
热议问题