jQuery Fadeout on Click or after delay

前端 未结 3 1194
逝去的感伤
逝去的感伤 2021-02-15 10:55

I am displaying a message box on a website. I would like to be able to have it either fadeout on click or after X seconds. The problem is that the delay() function

相关标签:
3条回答
  • 2021-02-15 11:32

    This would be an ideal use for jQuery 1.5's new Deferred objects:

    // a deferred object for later processing
    var def = $.Deferred();
    
    // resolve the deferred object on click or timeout
    $(".close-green").click(def.resolve);
    setTimeout(def.resolve, 5000);
    
    // however the deferred object is resolved, start the fade
    def.done(function() {
        $(".message-green").fadeOut("slow");
    });
    

    Working demo at http://jsfiddle.net/Nyg4y/3/

    Note that it doesn't matter that if you press the button the timer still fires - the second call to def.resolve() is ignored.

    0 讨论(0)
  • 2021-02-15 11:37

    You should change it to a setTimeout: http://jsfiddle.net/VRYBk/3/

    (in the jsfiddle link) I removed your delay line and replaced it with a standard setTimeout like:

    setTimeout(function(){
        $("#message-green").fadeOut("slow");
    },5000)
    

    As a note of WHY, is because JS is read top to bottom and it'll read your delay before you click and trigger the event. Therefore, even when you click the delay is being run causing all animation to pause.

    0 讨论(0)
  • 2021-02-15 11:46

    I fount it the best workaround suggested by Oscar Godson, I somehow added this to it:

    if (! $clicked.hasClass("search"))
    {
        setTimeout(function()
        {
            jQuery("#result").delay('1500').fadeOut('2800');
        },7000);
    }
    });
    

    His original suggestion is very useful:

    You should change it to a setTimeout: http://jsfiddle.net/VRYBk/3/

    (in the jsfiddle link) I removed your delay line and replaced it with a standard setTimeout like:

     setTimeout(function(){
          $("#message-green").fadeOut("slow");
     },5000)
    

    By Oscar Godson,

    0 讨论(0)
提交回复
热议问题