jquery “animate” variable value

风流意气都作罢 提交于 2019-12-03 09:02:49

问题


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 "smoothly".

Hope that you know what I mean.

Thank you!


回答1:


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




回答2:


try:

$({someValue: 0}).animate({someValue: 10}, {
    duration: 5000,
    step: function() { 
        $('#el').text(Math.ceil(this.someValue));
    }
});

<div id="el"></div>



回答3:


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

demo




回答4:


This should work for you:

var a = 1;
var b = setInterval(function() {
  console.log(a);
  a++;
  if (a == 10) { clearInterval(b); }
}, 500);



回答5:


Use setInterval :

percentage = 0;
startValue = 1;
finishValue = 5;
currentValue = 1;
interval = setInterval(function(){ 
   percentage ++; 
   currentValue = startValue + ((finishValue - startValue) * percentage) / 100;
   doSomething(currentValue);
   if (percentage == 100) clearInterval(interval);
 }, duration / 100)

function doSomething(val) { /*process value*/}



回答6:


​var blub = 1;
setTimeout(function () {
    blub = 10;
}, 5000);



回答7:


increment with setTimeout

x = 1

for(i=0;i<1000;i+=100){
  setTimeout(function(){
    console.log(x++)
  },i)
}



回答8:


Html mark up as
Html

<span id="changeNumber">1</span>

You can change its value after 5 seconds.
JQuery:

setInterval(function() {        
        $('#changeNumber').text('10');
    },5000);

Here is a Demo http://jsfiddle.net/Simplybj/Fbhs9/




回答9:


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;
};


来源:https://stackoverflow.com/questions/12317523/jquery-animate-variable-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!