How do you simulate typing using jQuery?

落花浮王杯 提交于 2020-01-21 04:35:39

问题


Like how the click() can be used to trigger a click event on an element, is there any way to simulate the typing of a string?


回答1:


Are you looking for a way to trigger the events associated with typing or do you want to append text to a container so that it looks like someone is typing? If you're looking for the events, then @Nick is absolutely correct in suggesting the methods for triggering the event. If the latter, you'll want to use a timer to replace the text/html of the container with successive substrings of your text. You might be able to get a better effect by appending successive span elements containing each letter if the text is very long -- this would reduce flashing as the text gets replaced and the layout changes momentarily.

EDIT: I was going to add an example, but it turns out there's a plugin for that already: jTypeWriter.




回答2:


You can use these events, depending on what you want:

  • .keydown()
  • .keypress()
  • .keyup()



回答3:


If you really want to simulate typing (i.e. including triggering the events and appending the text to an input or textarea element), you can use the jQuery simulate extended plugin:
http://j-ulrich.github.com/jquery-simulate-ext

Then you can use

$('input').simulate("key-sequence", {sequence: "This is a test", delay: 10});

to simulate the typing of the text "This is a test" with a 10ms delay between each key press.

Disclaimer: I'm the author of the plugin.



来源:https://stackoverflow.com/questions/2578211/how-do-you-simulate-typing-using-jquery

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