开发者

jQuery animate() function

I have a health bar (0% health = 0px width; 100% health = 100px):

<div style="width:<?php echo $health ?>"><?php echo $health ?></div>

After the user clicks an "Heal" button, he receives some health. Using the animate() function I made the bar to increase its width.

But I also need something 开发者_如何学Celse: to update the health value that is inside the div. I would like to animate this too (to have the same increasing values as the width).

But I don't know how. Can you help me please?

L.E.:

$('div').animate({ width: data.newhealth }, duration: 1500);

It's inside a getJSON function.

I thought the solution would be to replace the div's content with $('div').attr('width') very often during the animation, but I don't know how to do this either.


You can use the step option to the animate function. I have a working example here: http://jsfiddle.net/WxecS/

The important bit is:

$('#healer').click(function() {
    $('#div').animate({
        width: '100%'
    }, {
        step: function(now, fx) {
            $(this).text(Math.floor(now) + '%');
        }
    })
});


This wont animate the text, but will change it at the end:

http://jsfiddle.net/Ncv7Z/4/

$('#animate').animate({
    width: '100px'
}, 3000, function(){
    this.innerHTML = $(this).width();
});


use complete callback of .animate()
http://api.jquery.com/animate/

  $('#health').animate({
    width: 40
  },{ duration: 1000, step: function() {
    $("#health").text($(this).width());
  }});


use the step: function like described on jquery site

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜