问题
I want to create a jquery script that can write down a string inside a div character by character as if somebody would be typing it as the user is looking at the page.
I assume this would work with a recursive function using settimeout.
Help me with this please. Thanks.
回答1:
You can write one yourself.
- Make use of
setInterval() - Store a message in the array and pop the words / characters one by one
- Clear the interval when you're done
DEMO
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>
回答2:
jQuery Typewriter available here: https://github.com/chadselph/jquery-typewriter.
You can see the demo which is on the repo itself.
Here is an example of how it works:
$('.someselector').typewrite({
'delay': 100,
'extra_char': '',
'trim': true,
'callback': null
});
来源:https://stackoverflow.com/questions/24308108/jquery-display-string-character-by-character