有没有办法及时向前/向后跳转 jQuery 动画?
例如,如果我将元素上的动画设置为 10 秒,我可以跳到“5 秒”进入该动画吗?优选地,这可以用百分比来设置。
您可以停止当前动画,将动画对象的状态设置在其初始状态和最终状态之间的中间,然后将新动画开始到原始最终状态,但设置为一半时间。
这将跳转到动画的中间位置,然后从那里继续前进。
这是一个工作示例:http: //jsfiddle.net/jfriend00/FjqKW/。
这应该有你想要的一切,但百分比功能:
演示: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