如何使用 jQuery 模拟打字?
就像如何使用 click()
来触发元素上的单击事件一样,有没有办法模拟字符串的输入?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以根据需要使用这些事件:
.keydown()
.keypress()
.keyup()
You can use these events, depending on what you want:
.keydown()
.keypress()
.keyup()
如果您确实想模拟打字(即包括触发事件并将文本附加到输入或文本区域元素),您可以使用 jQuery 模拟扩展插件:
http://j-ulrich.github.com/jquery-simulate-ext
然后你可以使用
模拟文本
“This is a test”
的输入,每次按键之间有 10 毫秒的延迟。免责声明:我是该插件的作者。
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
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.
您是否正在寻找一种方法来触发与键入相关的事件,或者是否想要将文本附加到容器以便看起来有人正在键入?如果您正在寻找事件,那么@Nick 在建议触发事件的方法方面是绝对正确的。如果是后者,您将需要使用计时器将容器的 text/html 替换为文本的连续子字符串。如果文本很长,您可以通过附加包含每个字母的连续
span
元素来获得更好的效果 - 这会减少文本替换和布局瞬间更改时的闪烁。编辑:我本来要添加一个示例,但事实证明已经有一个插件: jTypeWriter。
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.