Suppose I have some div, and I use .animate({opacity:0},400, function(){});
for its children.
Is it ever possible then to get the remaining time for an animation to complete? eg, 200 ms remaining, or 0 if there's no animation?
Thanks.
问题:
回答1:
To help you better understand how you can use the step
function
[as posted by gdoron]
I created an example using the step function to get the remaining time:
(click the get state!
button to stop the animation and retrieve the remaining time!)
demo with distance
demo with opacity
Distance example jQuery:
var time = 4000;
var distance = 300;
var currentTime = 0;
$('#ball').animate({
left: distance
}, {
duration: time,
step: function (now, fx) {
currentTime = Math.round((now * time) / distance);
var data = fx.prop + ' ' + Math.round(now) + '; <b>' + currentTime + 'ms</b> ';
$('body').append('<p>' + data + '</p>');
},
easing: 'linear'
});
$('#getTime').click(function () {
$('#ball').stop();
$('body').prepend('<p>currentTime is:' + currentTime + ' ms; REMAINING: ' + (time - currentTime) + 'ms</p>');
});
- You can see how I used the
fx.prop
inside theanimation step
to get the (left
) property that is currently animated. - You can see how: knowing the animation time and the distance (opacity, whatever...) we can easily retrieve the 'stopped/paused' state by some simple math (
(now*time)/distance
) and thanks to the returnednow
value.
回答2:
I have no idea why do you need it, but the step
can help you extract this value:
Step Function
The second version of .animate() provides a step option — a callback function that is fired at each step of the animation. This function is useful for enabling custom animation types or altering the animation as it is occurring. It accepts two arguments (now and fx), and this is set to the DOM element being animated.
now: the numeric value of the property being animated at each step
fx: a reference to the jQuery.fx prototype object, which contains a number of properties such as elem for the animated element, start and end for the first and last value of the animated property, respectively, and prop for the property being animated.
docs
回答3:
Listen, never mind the step
function everybody keeps talking about. I once needed what you do and wrote my own that simply put it reverse engineered the time left by having a look at total animation time (should already be known to you since you once gave this number to jQuery) and the quotient of the current and target opacity. Then just multiply that quotient with the total animation time, have the sum subtracted from the total time. Simple as that.
Pseudo-code:
func calculate-time-left-in-a-running-fade-in-animation:
{
var current_opacity = $elem.css('opacity');
var target_opacity = this.getTargetOpacity();
var total = this.getTotalAnimationTime();
var quotient = current_opacity / target_opacity;
return total - quotient * total;
}