我发现另一个主题:

$({
    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');


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

最佳答案

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

09-28 00:51