在jQuery动画中向前跳?
问题描述:
有没有办法使jQuery动画在时间上向前/向后跳转?
Is there a way to jump a jQuery animation forward / backward in time?
例如,如果我在一个元素上设置了一个动画要花费10秒,我可以跳到该动画中的"5秒"吗?最好将其设置为百分比.
For example, if I have set an animation on an element to take 10 seconds, can I jump to '5 seconds' into that animation? Preferably, this could be set with a percentage.
答
除了百分比功能,它应该具有您想要的所有内容:
This should have everything you want but the percentage functionality:
演示: http://jsfiddle.net/SO_AMK/MHV5k/
jQuery:
var time = 10000; // Animation speed in ms
var opacity = 0; // Final desired opacity
function jumpAnimate(setOpacityTo, newOpacity, speed){ // I created a function to simplify things
$("#fade").css("opacity", setOpacityTo).animate({
"opacity": newOpacity
}, {
duration: speed // I used speed instead of time because time is already a global variable
});
}
$("#jump").click(function(){
var goTo = $("#jump-to").val(); // Get value from the text input
var setOpacity = (1 / time) * (time - goTo); /* The opacity that the element should be set at, i.e. the actual jump
Math is as follows: initial opacity / the speed of the original animation in ms * the time minus the desired animation stop in ms (basically the remaining time past the desired point) */
$("#fade").stop(); // Stop the original animation after the math is finished so that we have minimal delay
jumpAnimate(setOpacity, opacity, time - goTo); // Start a new animation
});
jumpAnimate(1, opacity, time); // Start the initial animation