iOS 9 - keyup event not firing

自古美人都是妖i 提交于 2019-11-30 14:02:05

问题


Is anybody else having problems with the keyup event in iOS 9 not firing?

Just a simple test bed replicates the issue for me.

<input id="txtInput" />

Vanilla JS:

document.getElementById('txtInput').onkeyup = function () {
    console.log('keyup triggered');
}

jQuery:

$('#txtInput').on('keyup', function () {
    console.log('keyup triggered');
});

Neither fire...


回答1:


I suggest using the keypress event on browsers with touch screens. I know that you can't really detect touch screen screens, though, so it leaves you with a few options that your situation will likely dictate.

  1. Attach both events keyup and keypress. This would likely be dependent on how much processing is going on and if you are getting double-fires in some browsers.
  2. Attempt to determine whether the browser is a touch screen (like using Modernizr), and then attach a fallback handler like change.

Either way, you end up with two event listeners.




回答2:


$('#yourid').bind('keypress', function(e) {
    // This will work
});



回答3:


It's not pretty, but a work around is to bind to keydown to capture which key has been pressed, and input if you want to obtain the value, including the key typed:

(function () {
    var keyCode;

    $('#txtInput')
        .on('keydown', function (e) {
            // value not updated yet
            keyCode = e.keyCode;

            // Enter key does not trigger 'input' events; manually trigger it
            if (e.keyCode === 13) $(this).trigger('input');
        })
        .on('input', function (e) {
            console.log(keyCode, this.value);
        });
}());

If you type 'a' the following occurs:

  1. keydown fires.
  2. e.keyCode is set to the ASCII value of the key pressed.
  3. this.value is '' (i.e. the same before 'a' has been typed).
  4. input fires.
  5. e.keyCode is undefined.
  6. this.value is 'a'.

You can also manually trigger an input event if the enter (13) key is pressed; input isn't fired by this key by default.



来源:https://stackoverflow.com/questions/33152960/ios-9-keyup-event-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!