从数字到目标数字脚本计数,并在多个框中使用它

时间:2013-08-11 20:53:07

标签: javascript jquery

我发现了另一个话题:

$({
    countNum: $('.skill-counter').text()
}).animate({
    countNum: 90
}, {
    duration: 2000,
    easing: 'linear',
    step: function () {
        $('.skill-counter').text(Math.floor(this.countNum) + 1 + ('%'));
    }
});

我想改变的是将它放在一个函数中并在具有不同计数值的多个框中使用它。

到目前为止我做了什么:

var count = function (counTo, divName) {
    this.counTo = 0;
    $(counTo).animate({
        counTo: counTo
    }, {
        duration: 2000,
        easing: 'linear',
        step: function () {
            $(divName).text(Math.floor(counTo) + 1 + ('%'));
        }
    });
};

count(90, 'box1');
count(70, 'box2');
count(50, 'box3');

它不起作用,可能这是正常的,因为它是完全错误的!那我怎么能这样做呢?

1 个答案:

答案 0 :(得分:2)

var count = function (countTo, divName) {
    //Set the starting object as {countTo:0}
    $({countTo: 0}).animate({countTo: countTo}, {
        duration: 2000,
        easing: 'linear',
        step: function () {
            //get the reference to the value using 'this'
            $(divName).text(Math.floor(this.countTo) + 1 + ('%'));
        }
    });
};

//Pass resolvable selectors
count(90, '#box1');
count(70, '#box2');
count(50, '#box3');

<强> Demo fiddle