jQuery callback not waiting on fadeOut

这一生的挚爱 提交于 2020-01-13 09:50:10

问题


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.


回答1:


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.




回答2:


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

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


来源:https://stackoverflow.com/questions/1678013/jquery-callback-not-waiting-on-fadeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!