automatically press keyboard with jQuery?

前端 未结 6 1916
臣服心动
臣服心动 2021-01-19 04:06

Is it possible with jQuery to automatically simulate a press on a keyboard, f.ex. inside an html input field?

As explanation: If I press the a inside an

相关标签:
6条回答
  • 2021-01-19 04:18

    Nope. Not possible in Javascript to simulate actual keyboard key press. Keyboard keypress involves lot more process which is outside Javascript/Browser.

    Alternatively you can simulate key press event, but I guess you don't want to call the key press.

    0 讨论(0)
  • 2021-01-19 04:24

    trigger does help, because it fires an event...and that is the only thing you are interested in browser...everything before that is a matter of OS (which you cannot reach, since you are building inside a browser...unless you build some activeX control). So, this should work:

    var e = $.Event("keypress");
    e.which = <some_key_code>;
    $("<your_input_selector>").trigger(e);
    

    As you can see here keypress event is sent when browser registers keyboard input. Difference between keypress and keydown is: "If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character...". You can decide which one you will use depending on your use case.

    0 讨论(0)
  • 2021-01-19 04:26

    I don't think there is a javascript API for interacting directly with the keyboard. I would suggest combining a change in the field's value with an event handler firing that would normally correspond to the keyboard press, as you mentioned, so that behavior on the field is triggered as normal.

    0 讨论(0)
  • 2021-01-19 04:31

    You can try something like.

    $("inputSelector").trigger($.Event("keypress", { keyCode: 97 }));
    

    Pass the keycode of whatever key you want.

    0 讨论(0)
  • 2021-01-19 04:31

    Mimicking a keypress in JavaScript (and therefore jQuery) boils down to inserting the "typed" character where you need it and firing off any relevant handlers (i.e., with trigger).

    0 讨论(0)
  • 2021-01-19 04:42

    It seems to me as if the goal is not necessarily to mimic a native browser keypress event, but to manipulate text inside an input field.

    If I'm right, you can fetch the .prop('selectionStart') and .prop('selectionEnd') values and overwrite any characters within those indexes by the character(s) you want to "keypress". You can accompany this by triggering of appropriate keyboard events.

    I've never worked on text selection before. I know IE handles things differently than normal browsers, so you'll need to look into this topic and find a cross-browser solution if you choose to walk this path. To make things perfect, you'll need to change the selection properties after modifying the input's value as if it were a native paste.

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