Trigger a keypress with jQuery…and specify which key was pressed

前端 未结 2 1837
清酒与你
清酒与你 2020-12-06 08:32

I would like to have an input element (type=text) or textarea element that validates dynamically by triggering specific keystrokes. This will be used for Chinese pinyin inp

相关标签:
2条回答
  • 2020-12-06 09:00

    You may not have much luck triggering keypress - I'm fairly sure that unless the keypress is trusted (i.e. originates from the browser), it won't be picked up.

    However, you can do text replacement and insert the carat back where it was - instead of shooting it to the end of the string. You need to use setSelectionRange and createTextRange (for IE).

    I've put together a little demo - the replacements you'll see don't match real words, but it shows how it works:

    http://jsbin.com/emudi/ (to edit the source http://jsbin.com/emudi/edit)

    The trick is to take note of where the carat is, replace the found word using substr (rather than regex to avoid replacing the wrong matches) and then re-placing the carat at the end of the new word.

    The replacement is triggered on the space press or blurring the away. A note on this - you could trigger the replacement on a specific character (i.e. the '2') - but I wouldn't recommend searching for replacements on every keypress.

    0 讨论(0)
  • 2020-12-06 09:09

    Also, for simple code controlling the "caret" in a cross-browser way this could be useful:

    http://javascript.nwbox.com/cursor_position/

    a bit late with the answer but I am sure you will still find this old stuff useful.

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