Why can't I delay a remove call with jQuery

前端 未结 3 1909
野的像风
野的像风 2021-02-07 03:12

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

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

Unfortunately,

3条回答
  •  灰色年华
    2021-02-07 03:56

    .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();
    });
    

提交回复
热议问题