jQuery callback not waiting on fadeOut

2019-06-19 19:12发布

It seems to me the following code should produce these results:

mademoiselle
demoiselle
mesdemoiselles

Instead, as "ma" fades out, "mes" fades in making the sequence:

mademoiselle
madesdemoiselles
mesdemoiselles

The code:

<span class="remove">ma</span><span class="add">mes</span>demoiselle<span class="add">s</span>

$(document).ready(function() {
   $(".remove").fadeOut(4000,function(){
       $(".add").fadeIn(5000);      
   });
});

Edit: I found an empty span that if I remove makes the bug go away:

<span class="remove">ma</span><span class="add">mes</span>demoiselle<span class="remove"></span><span class="add">s</span>

The problem is: The php code generating this is using the spans as placeholders. I'll str_replace them if I have to, but I'm curious why this is happening.

2条回答
爷的心禁止访问
2楼-- · 2019-06-19 19:33

Ok, so I managed to reproduce your problem see the example at http://jsbin.com/ocaha.

What's happening is that jQuery can see that your empty <span> does not need to be faded out. Therefor it considers the animation done and executes for 0ms instead of the expected 4000ms. So it immediately starts fading in all of the .adds.

To prevent this behaviour, I would filter away all empty elements from the selection. Like this:

$(document).ready(function() {
   $(".remove")
               .filter(function(){ return ! $(this).is(":empty"); })
               .fadeOut(4000, function(){
     $(".add").fadeIn(5000);
   });
});

See working example at http://jsbin.com/ovivi.

查看更多
Animai°情兽
3楼-- · 2019-06-19 19:38

Change ":empty" to ":hidden" if not working:

$(document).ready(function() {
   $(".remove")
               .filter(function(){ return ! $(this).is(":hidden"); })
               .fadeOut(4000, function(){
     $(".add").fadeIn(5000);
   });
});
查看更多
登录 后发表回答