问题
如何在上一个切换动画完成之前阻止jquery切换函数运行?
我有一个简单的脚本来显示或隐藏数据,具体取决于是否选中复选框。
查询
$('.a').hide();
$('#CB').change(function () {
if ($(this).is(':checked')) {
$('.b').fadeOut(100, function () {
$('.a').fadeIn();
});
} else {
$('.a').fadeOut(100, function () {
$('.b').fadeIn();
});
}
});
问题
当事件连续激发时,两个元素,在这种情况下,.a
和.b
一起可见。我认为这是因为在再次启动函数之前,先前的请求没有完成。
点击演示
http://jsfiddle.net/keypaul/PbS33/5/
$('.a').hide();
$('#CB').change(function () {
if ($(this).is(":checked")) {
$('.b').stop().fadeOut(100, function () {
$('.a').stop().fadeIn();
});
} else {
$('.a').stop().fadeOut(100, function () {
$('.b').stop().fadeIn();
});
}
});
使用jquery stop((
http://api.jquery.com/stop/
你说得对。jQuery中的动画是异步工作的,因此有时它们可以同时运行。
为了回答你的问题,我想你已经在问题标题中回答了。
使用队列
设置一个标志,将其命名为类似isFading
的名称,当$("#CB")
更改时为true时,则将其排队。
var isFading=false;
var animationQueue = [];
$('#CB').change(function () {
if(isFading){
if ($(this).is(':checked')) {
animationQueue.push(fadeOutFadeIn);
}
else {
animationQueue.push(fadeInFadeOut);
}
}
else{
if ($(this).is(':checked')) {
fadeOutFadeIn();
} else {
fadeInFadeOut();
}
}
);
function fadeOutFadeIn(){
isFading=true;
//insert your fadeout fadein code here
isFading=false;
if(animationQueue.length > 0)
//you're now calling the queued animation to go through
animationQueue.splice(0,1)();
}
function fadeInFadeOut(){
isFading=true;
//insert your fadein fadeout code here
isFading=false;
if(animationQueue.length > 0)
//you're now calling the queued animation to go through
animationQueue.splice(0,1)();
}