【问题标题】:jquery display string character by characterjquery逐个字符显示字符串
【发布时间】:2014-06-19 13:43:38
【问题描述】:
我想创建一个 jquery 脚本,它可以在 div 中逐个字符地写下一个字符串,就好像有人会在用户查看页面时键入它一样。
我假设这将与使用 settimeout 的递归函数一起使用。
请帮帮我。谢谢。
【问题讨论】:
标签:
jquery
string
recursion
character
【解决方案1】:
你可以自己写一个。
- 使用
setInterval()
- 在数组中存储一条消息,并逐个弹出单词/字符
- 完成后清除间隔
jQuery:
// Consturct a message, transform it to an array using .split() and reverse it
// If you want to print out one word at a time instead of a character at a time
// Change .split('') to .split(' ')
var $message = 'This is a message to be rendered'.split('').reverse();
// Set the frequency of your 'pops'
var $timeout = 1000;
var outputSlowly = setInterval(function() {
// Add text to the target element
$('#target').append($message.pop());
// No more characters - exit
if ($message.length === 0) {
clearInterval(outputSlowly);
}
}, $timeout);
HTML:
<p id="target"></p>