jQuery animate of custom value (not a CSS property)

流过昼夜 提交于 2019-11-29 03:01:58

Just stumbled upon this while searching for the same thing and the correct answer appears to be

$({foo:0}).animate({foo:100}, {
    step: function(val) {
        // val takes values from 0 to 100 here
    }
})

Found on http://james.padolsey.com/javascript/fun-with-jquerys-animate/

Annoyingly it's not possible to run the animate function without actually supplying some CSS properties for it to work on (it doesn't give you the values in between).

You don't need to even have the animation working on the actual element (or variable) you want to change so it's possible to hack it to work using the step argument as described by @Andrew like so:

$('<div/>').css({ height: _your_start_value }).animate({
    height: _your_end_value
}, { 
    step: function (currentValue) {
        //do what you need to with the current value..
    }
});

However, this is pretty inefficient as it's changing the (although unattached) element's height CSS property needlessly. It's better to just use a "tweening" library such as Tween JS to do this kind of thing.

If you are looking to "spin" something, you can do that with css and therefore, you can use the jQuery animate function.

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