开发者

keypress event not working properly in safari and in Firefox with jQuery 1.3

开发者 https://www.devze.com 2022-12-16 08:25 出处:网络
The code snippet is here If I replace keypress with keyup or keydown, it works fine. As per jQuery documentation event.which should work fine.

The code snippet is here

If I replace keypress with keyup or keydown, it works fine. As per jQuery documentation event.which should work fine.

Update:

Very bottom of this page s开发者_开发技巧ays:

If you need to detect these keys, do yourself a favour and search for their keyCode onkeydown/up, and ignore both onkeypress and charCode.

Looks like keypress is not very reliable.

Update2:

keypress event does work in firefox and in Safari. However it does not detect left and right arrow keypress. http://docs.jquery.com/Events/keypress


Keypress is a confusing event. While keydown and keyup will tell you which specific key on your keyboard is down or just came back up, the keypress event is supposed to tell you what character would appear on the screen, that's why the jquery documentation that you referenced says:

For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress.

To make things worse Safari doesn't trigger keypress events for stuff that doesn't write something onto the screen—that’s why arrow keys won't work. Firefox, however, does trigger keypress events for arrow keys. Both are reasonable implementations of the spec, so don’t expect either to change. That's why there was the suggestion to just stick with keydown or keyup.

However, it looks like you want to take advantage of how the keypress event repeats (in Firefox) when a key is held down and you want to do this with an arrow key. If that's the case, you need to write a handler that looks at both keydown and keypress. here are the two different ways browsers react to an arrow key being held down:

  • Firefox registers a keydown event and also repeats keypress events (note: just hitting the key once will register both a keydown and a keypress event)
  • Safari registers a keydown event and repeats the keydown event

A quick hack to make that work reasonably well for arrow keys and get the key repeats to work is:

function moveItem(evt) {
    // do something with `this` and evt.keyCode here...
}

$(document.documentElement)
    .keypress(function(evt) {
        if ($.data(this, '_lastKeyEvent') != 'keydown') {
            // since firefox will do both a keydown and a keypress for the first
            // keydown, we ignore the very first keypress
            moveItem.call(this, evt);
        }
        $.data(this, '_lastKeyEvent', 'keypress');
    })
    .keydown(function(evt) {
        moveItem.call(this, evt);
        $.data(this, '_lastKeyEvent', 'keydown');
    });
0

精彩评论

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