使javascript动画条同步到动画百分比

时间:2013-11-05 14:02:12

标签: javascript jquery-animate percentage

我遇到的问题是我无法弄清楚如何使动画条同步到 现在我看起来很好,但是当我将值'43'更改为'100'时,百分比计数器会变慢。

示例代码:

$(document).ready(function(){
                $(".barInner").animate({
                    width: 43 + "%",
                    opacity: 1
                }, 2500 );

                var display = $('.barInner');
                var currentValue = 0;
                var nextValue    = 43;

                var diff         = nextValue - currentValue;
                var step         = ( 0 < diff ? 1 : -1 ); 

                for (var i = 0; i < Math.abs(diff); ++i) {
                    setTimeout(function() {
                        currentValue += step
                        display.text(currentValue + "%");
                    }, 54 * i)   
                }
            });

http://jsfiddle.net/vTKw7/

提前致谢,

尼克

1 个答案:

答案 0 :(得分:2)

您无法以您希望的方式同步.animate()setTimeout()。尝试使用setTimeout控制进度条的宽度并同时显示百分比数字。

        $(document).ready(function () {

            var display = $('.barInner');
            var currentValue = 0;
            var nextValue = 100;
            var diff = nextValue - currentValue;
            var step = (0 < diff ? 1 : -1);

            for (var i = 0; i < Math.abs(diff); ++i) {
                setTimeout(function () {
                    currentValue += step;
                    display.text(currentValue + "%");
                    $(".barInner").css({
                        width: currentValue + "%",
                        opacity: 1
                    });
                }, 54 * i)
            }
        });

http://jsfiddle.net/mblase75/6TMWm/

或者,使用.stop().animate()来平滑一点:

                    $(".barInner").stop().animate({
                        width: currentValue + "%",
                        opacity: 1
                    },50);

http://jsfiddle.net/mblase75/6TMWm/1/