Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

javascript - Can jQuery's .animate() method be made to affect variables, rather than CSS properties?

I started writing some JS code to cause a variables value to increase over time, up to a target value, with some form of 'ease-in'.

I realised that jquery already does this in it's .animate() method. Of course, the method is for manipulating CSS properties, not general variables.

My question is, is there anything that can be done to hack it so that the method affects a variable, rather than a CSS property?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can animate variables. Demo here

$({ n: 0 }).animate({ n: 10}, {
    duration: 1000,
    step: function(now, fx) {
        $("div").append(now + "<br />");
    }
});

In this example, I am animating n from 0 to 10 in 1 second. The step function is called during animation and from there you can retrieve the current value in now.

Personally, I used this technique to animate several css properties simultaneously in a non linear fashion.

Animate runs by modifying the value of properties declared in JS objects. Although animate is designed to change CSS scalar values, it can also safely be used for any generic property, as long value is a scalar one.
In fact, you can think of CSS as a set of JS objects, where properties are for example, top, margin etc.

Note that the following scripts do the same. They change CSS left from 0 to 10

$("#test").css('left', 0).animate({ left: 10 }, 1000);

is the same as

$({ left: 0 }).animate({ left: 10 }, {duration: 1000, step: function(now, fx) {
  $("#test").css('left', now);
}});

or, without using the now parameter

var obj = { left: 0 };
$(obj).animate({ left: 10 }, {duration: 1000, step: function() {
      $("#test").css('left', obj.left);
}});

To see them in action click here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...