Why can't I delay a remove call with jQuery

不羁的心 提交于 2019-12-20 17:27:03

问题


I would like for a div to fadeOut and then be removed:

 $('#div').delay(1000).fadeOut(300);
 $('#div').delay(1300).remove();

Unfortunately, this just directly removes the div, with no delays. Why is it that I can't get the remove action to be delayed? What solutions are there?

Thanks


回答1:


If you want the element to be removed after it's done being faded out, you can fadeOut's callback parameter.

$('#div').delay(1000).fadeOut(300, function(){
   $(this).remove();
});



回答2:


.delay() only works with methods that go through the animation queue. Thus, it works for .fadeOut() (an animation), but not .remove() (not an animation).

To show you how specialized this is, this doesn't delay:

$('#div').delay(1000).hide();

But, this does:

 $('#div').delay(1000).hide(1);

Putting a duration on the hide method turns it into an animation which then uses the animation queue, which then works with .delay().

To remove the item with a delay, you can use a setTimeout() call:

setTimeout(function() {
    $('#div').remove();
}, 1300);

or get a bit tricky and use a completion function on an animation like this:

$('#div').delay(1000).hide(1, function() {
    $(this).remove();
});



回答3:


You can try something like this.

$('#div').delay(1000).fadeOut(300,function(){
    setTimeout(function(){
      $('#div').remove()
    } ,1300);

});

I think it works as it should. Hope it helps



来源:https://stackoverflow.com/questions/8100772/why-cant-i-delay-a-remove-call-with-jquery

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