jquery “animate” variable value

后端 未结 9 781
说谎
说谎 2021-02-04 05:36

I need to \"animate\" a variable with jquery.

Example: The variable value is 1. The value should be 10 after 5 seconds. It should be increase \"smoothl

相关标签:
9条回答
  • 2021-02-04 05:58

    try:

    $({someValue: 0}).animate({someValue: 10}, {
        duration: 5000,
        step: function() { 
            $('#el').text(Math.ceil(this.someValue));
        }
    });
    
    <div id="el"></div>
    
    0 讨论(0)
  • 2021-02-04 05:59

    increment with setTimeout

    x = 1
    
    for(i=0;i<1000;i+=100){
      setTimeout(function(){
        console.log(x++)
      },i)
    }
    
    0 讨论(0)
  • 2021-02-04 06:02

    This should work for you:

    var a = 1;
    var b = setInterval(function() {
      console.log(a);
      a++;
      if (a == 10) { clearInterval(b); }
    }, 500);
    
    0 讨论(0)
  • 2021-02-04 06:04

    What you require is the step parameter in the $().animate function.

    var a = 1;
    jQuery('#dummy').animate({ /* animate dummy value */},{
        duration: 5000, 
        step: function(now,fx){ 
            a = 1 + ((now/100)*9); 
        }
    });
    

    demo

    0 讨论(0)
  • 2021-02-04 06:07

    As addition to Ties answer - you dont event need to append dummy element to the DOM. I do it like this:

    $.fn.animateValueTo = function (value) {
    
        var that = this;
    
        $('<span>')
            .css('display', 'none')
            .css('letter-spacing', parseInt(that.text()))
            .animate({ letterSpacing: value }, {
                duration: 1000,
                step: function (i) {
                    that.text(parseInt(i));
                }
            });
    
        return this;
    };
    
    0 讨论(0)
  • 2021-02-04 06:12

    representation

    var snail = {speed:0};
    $(snail).animate({speed: 10}, 5000);
    

    demo

    0 讨论(0)
提交回复
热议问题