Get .val() on keydown *not* keyup

◇◆丶佛笑我妖孽 提交于 2020-02-03 18:20:12

问题


I'm writing a library that amends a widget to a text area, so I need to detect when the user starts typing something:

this.$input.bind('keydown keyup', function() {
    if (this.$input.val() == …) { … }
}

The .val() only updates when keyup is triggered. That's too much of a delay. I want to know the state of the input box on keydown. Do you know of a library that improves .val()?


回答1:


too late? can't imagine a scenario where 10ms would make that much of a difference, but you could always examine the event args and get the char from there. or try keypress.

edit: there's also the input event that gets fired as soon as the input changes (before keyup, but after the value changes);




回答2:


The only way to determine the character at keydown/keypress is by using the event.keyCode or event.which property (where event is an object, passed as a first argument to the event listener function).

Swap your events for the keypress event. This event listener is fired while the key is pressed down. keydown and keyup are only fired once. During the keydown/keyup event, multiple characters could have been added.




回答3:


Found a seemingly perfect solution. Uses aforementioned HTML5 oninput with onpropertychange fallbacks for IE. Brilliant. Fantastic. Other happy words.




回答4:


For a keypress (ex. the "a" key), the keydown event is triggered before the "a" is appended to the text input. You could detect the event type, and whether the .keyCode (or .which) event property was a key in the printable range, and attempt to predict what .val() might return after the keyup event, but this is a bad idea.

this.$input.bind('keydown keyup', function(e) {
    var val = this.$input.val();

    if (e.type == 'keydown') {
        // Here is where you would check to see if e.keyCode was a printable
        // character.  Note that key codes differ from ASCII codes. For
        // example, the "a" key will return key code 65, which is actually
        // the ASCII code for "A", so you would need to check for the presence
        // of shift keys and such.  Again, this is a bad idea :)
        val += String.fromCharCode(e.keyCode);
    }

    if (val == …) { … }
}


来源:https://stackoverflow.com/questions/7590011/get-val-on-keydown-not-keyup

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