像“循环”一样计数

时间:2014-01-11 21:50:21

标签: javascript jquery loops numbers counting

我想这样做就像一个循环,完成后,再次像循环一样启动计数器

示例:

http://jsfiddle.net/4v2wK/226/

// Animate the element's value from x to y:
  $({someValue: 40000}).animate({someValue: 45000}, {
      duration: 3000,
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $('#el').text(commaSeparateNumber(Math.round(this.someValue)));
      }
  });

 function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }
    return val;
  }

2 个答案:

答案 0 :(得分:1)

function counter(startVal, endVal) {
    $({someValue: startVal}).animate({someValue: endVal}, {
      duration: 3000,
      complete: function() { counter(startVal, endVal) },
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $('#el').text(commaSeparateNumber(Math.round(this.someValue)));
      }
     });
}

以下是一个工作示例:JSFiddle

答案 1 :(得分:1)

有了这个:

(function counter() {
  $({someValue: 40000}).animate({someValue: 45000}, {
      duration: 3000,
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $('#el').text(commaSeparateNumber(Math.round(this.someValue)));
      },
      complete: counter
  }); 
})();

http://jsfiddle.net/edgarinvillegas/4v2wK/227/