jQuery keyboard events

后端 未结 4 805
萌比男神i
萌比男神i 2020-11-29 13:31

Using jQuery, I would like to capture a keyboard event that is:

  • before the user lifts their finger from the key
  • after the characters
相关标签:
4条回答
  • 2020-11-29 14:05

    You can use setTimeout:

    $('input').keypress(function() {
        var that = this;
        setTimeout(function() {
            // read that.value
        }, 0);
    });
    

    Live demo: http://jsfiddle.net/HpXuU/8/

    0 讨论(0)
  • 2020-11-29 14:08

    You could listen on keydown event and store the value in a variable. That variable would have the value as it was before the new input, and the new input would be included in the keyup event

    UPDATE:

    Ok, I misunderstood your requirements, but there isn't an event that would meet your needs. The only thing I can think of to simulate this behaviour is the following:

    • listen on keydown/keypress
    • get the value from the event object (get event.which, then convert it to actual value)
    • use a variable like I mentioned in the original advice and concatenate the new input to it

    Here is a fiddle: http://jsfiddle.net/HpXuU/13/

    This is obviously not a perfect solution, as it needs some (one might argue unnecessary) work to get done right. I would advise to rethink your needs, but if this behavior is absolutely what you need, I think this is a step in the right direction.

    0 讨论(0)
  • 2020-11-29 14:09

    Use keyup event, an example on jsFiddle

    $("textarea").keyup(function(e){
       alert($(this).val());
    });
    

    It happens after you lift the key. I don't know what you want to achieve, but you can store the state before lifting the key (on keydown or keypress) and restoring later if needed. You also can stop the output in the keyup event using e.preventDefault(), so even after the key is up it will not register the values in the area.

    0 讨论(0)
  • 2020-11-29 14:14

    You can use the input event, which works in recent versions of all major browsers:

    var input = document.getElementById("your_input_id");
    input.oninput = function() {
        alert(input.value);
    };
    

    Unfortunately, it doesn't work in IE <= 8. However, in those browsers you can use the propertychange event on the value property instead:

    input.onpropertychange = function() {
        if (window.event.propertyName == "value") {
            alert(input.value);
        }
    };
    

    SO regular JavaScript answerer @Andy E has covered this in detail on his blog: https://web.archive.org/web/20140626060232/http://whattheheadsaid.com/2011/10/update-html5-oninput-event-plugin-for-jquery

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