Here is my code. For some reason the entire String fades in at one time instead of each individual character. My console.log shows the characters are being executed one by one. Why is the entire string fading in at one time? Shouldn't the statement within the for loop execute for each character?
<!DOCTYPE html>
<head>
<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
<script>
$(function() {
string = " David";
for(i = 0; i < string.length; i++) {
$('#fadeIn').append(string[i]).delay(1000).hide().fadeIn(1000);
console.log(string[i]);
}
});
</script>
</head>
<body>
<div id="fadeIn" style="color: #000"></div>
</body>
</html>
To get the individual letters to fade in, they need to be DOM elements.
$(function() {
var string = " David";
var q = jQuery.map(string.split(''), function (letter) {
return $('<span>'+letter+'</span>');
});
var dest = $('#fadeIn');
var c = 0;
var i = setInterval(function () {
q[c].appendTo(dest).hide().fadeIn(1000);
c += 1;
if (c >= q.length) clearInterval(i);
}, 1000);
});
The for loop is executing the delay, append and fade in on all letters at once, so they will show at the same time. You want to do this with a setInterval instead:
var string = "David",
stringCount = 0;
setInterval(function(){
$('#fadeIn').append(string[stringCount]);
stringCount += 1;
},1000);
Working fiddle: http://jsfiddle.net/bGsa3/
I thought about this for a bit, and believe this would be better served with $.Deferred()
This allows the animation to be whatever you want, and if you change that, it does not impact the rest - the animation controls the timing, firing "done" and starting the next letter when it completes by triggering the custom event.
Nothing fancy, just does what you asked.
Simple markup:
<div id="animator"></div>
For example:
var myString = " Freddy The Mark";
var i = 0; // used to iterate the string, could be done other ways
var myEffect = function (c) {
return $("#animator").append(c).fadeIn(800).delay(800).fadeOut(1);
};
$("#animator").on("show", function () {
var c = myString[i];
$.when(myEffect(c)).done(function () {
i++;
if (i < myString.length) {
$('#animator').trigger('show');
} else {
$("#animator").show();//show it when we are done
}
});
});
$('#animator').trigger('show'); //get started by firing the custom event handler
Put it all together in a sample: http://jsfiddle.net/N8eRN/1/
来源:https://stackoverflow.com/questions/18214066/fade-in-string-characters-with-jquery