[英]How to wait for one jquery animation to finish before the next one begins?
[英]Javascript wait for one animation to finish before the next one begins
我有一个Javascript函数(不是jQuery),可以对框的打开或关闭进行动画处理。 问题是我关闭了包装盒,运行了一些更改内容的代码,然后重新打开它。
现在的“问题”是其余的代码太快了,因此它甚至从未设法关闭,更不用说重新打开了。 我可以使动画不允许在内部再次运行,除非最后一个动画完成,但是如果我想在两个不同的对象上运行两次动画,这将限制动画的运行。
那么预防这种情况的最佳方法是什么? 我的想法可能是超时,该超时要求在运行动画之前先等待,但这似乎很hacky,我不确定是否有更好的解决方案?
谢谢。
function animate(boxID, step, limit, speed){
// Add timeout property to animate function/object if it doesn't exist already
if(animate.timeout == undefined) animate.timeout = 0;
// Clear the current timeout
clearTimeout(animate.timeout);
// Initialize box and current box height
var box = document.getElementById(boxID);
var h = box.clientHeight;
// Check if we want the step needs to be changed to pos/neg based on which direction is wanted to be going
if(h < limit && step < 0 || // Positive
h > limit && step > 0){ // Negative
step *= -1;
}
// If the step is positive, then we need to be below the limit, or if negative, then greater than the limit
if((step > 0 && h <= limit - step) || (step < 0 && h >= limit - step)){
// Set new height
box.style.height = h + step + "px";
// Start new timeout
animate.timeout = setTimeout(function(){ animate(boxID, step, limit, speed, 1); }, speed);
}
else{
box.style.height = limit + "px"; // Set to the exact height
}
}
您可以通过回调来实现。 您的animate
函数有一个plus参数,当动画准备就绪时要调用的函数:
function animate(boxID, step, limit, speed, onReady){
动画制作完成后,您将其称为:
else{
box.style.height = limit + "px"; // Set to the exact height
if (onReady) { onReady(); }
}
您还希望将回调转发给超时调用:
setTimeout(function(){ animate(boxID, step, limit, speed, 1, onReady); }, speed);
因此,您可以像这样调用多个框的函数:
animate(box1_id, close_step, close_limit, close_speed, function () {
// now box1 is closed, put something in. then:
animate(box1_id, open_step, open_limit, open_speed, null);
});
// then the same for box2, etc…
这样box1和box2将同时关闭,并且只有在将东西放入里面之后才重新打开。
另外,您不能将计时器存储在该函数上,因为现在它在多个框中运行。 因此,您可以将其存储在盒子上,也可以存储在单独的位置。 例如,在函数外部创建一个对象,然后将所有框的计时器放入其中:
var timeouts = {};
timeouts[box1_id] = setTimeout(…);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.