简体   繁体   中英

animate every char of an html element text using jquery?

i want to animate a string of text taken from an html element using jquery:

<h1>Animate</h1>

for the jquery part:

$(document).ready(function() {

$( "h1" ).animate({ fontSize: "90px" }, 1500 )
     .animate({ fontSize: "50px" }, 1500 );

});

this animates the whole h1 text value, however i want to animate each character in the h1 text.

the second jquery part:

$(document).ready(function () {

    var animateChar = $("h1").text();
    for(i=0; i<animateChar.length; i++) {

        //alert(i + ': ' + animateChar.charAt(i));
        // for every animateChar.charAt[i] want to run this
        //jquery animation.
        //$( "h1" ).animate({ fontSize: "90px" }, 1500 )
        //.animate({ fontSize: "50px" }, 1500 );

        }
 });

this is the bit where im stuck. thanks

You can use jQuery functions on DOM elements. Not on characters apart. You should use different DOM elements for each character:

<span>A</span><span>N</span><span>I</span>...

with something like this must do the trick

$('span').each(function() {
    var that = $(this);
    setTimeout(function() { 
        that.animate({ fontSize: "90px" }, 1500 )
            .animate({ fontSize: "50px" }, 1500 );
    },that.index()*100);
});​

-edit-

working jSFIDDLE

-edit 2-

without messy HTML JSFIDDLE (well it's still messy, but javascript makes it messy ;) )

<span class="animate">A</span><span class="animate">n</span><span class="animate">i</span><span class="animate">m</span><span class="animate">a</span><span class="animate">t</span><span class="animate">e</span>

$(document).ready(function() {

   var count = 0;       

   function animation(elm) {
       if(count == $(".animate").length)
       {
          clearInterval(id);
          return;
       }

       $( elm ).animate({ fontSize: "90px" }, 1500 )
     .animate({ fontSize: "50px" }, 1500 );
     count++;
   }

   var id = setInterval(animation($(".animate")[count]), 3200);//Give time for animation to run.

});

This will animate each character.

If you want to keep your HTML clean, I'd add the following method to wrap your characters in span tags. Execute this onLoad using wrapCharacters($("h1")) before you animate anything, then animate characters returned by $(".animate") .

function wrapCharacters(obj)
{
    var html = '';
    var text = obj.text();
    for (var i = 0; i < text.length; i++)
    {
        html += '<span class="animate">' + text[i] + '</span>';
    }
    obj.html(html);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM