简体   繁体   English

点击或延迟后的jQuery Fadeout

[英]jQuery Fadeout on Click or after delay

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. 我希望能够在点击或X秒后淡出。 The problem is that the delay() function takes the place over the click() function making it so even if you click close you still have to wait the time. 问题是delay()函数取代了click()函数,因此即使你单击关闭,你仍然需要等待时间。

Here is the jQuery 这是jQuery

$(document).ready(function() {    
$(".close-green").click(function () {
        $("#message-green").fadeOut("slow");
    });

    //fade out in 5 seconds if not closed
    $("#message-green").delay(5000).fadeOut("slow");

})

I also set up a simple jsfiddle. 我还设置了一个简单的jsfiddle。 To see the problem comment out the delay line http://jsfiddle.net/BandonRandon/VRYBk/1/ 要查看问题注释延迟线http://jsfiddle.net/BandonRandon/VRYBk/1/

You should change it to a setTimeout : http://jsfiddle.net/VRYBk/3/ 你应该把它改成setTimeouthttp//jsfiddle.net/VRYBk/3/

(in the jsfiddle link) I removed your delay line and replaced it with a standard setTimeout like: (在jsfiddle链接中)我删除了你的延迟线,并将其替换为标准的setTimeout如:

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. 作为一个原因的说明,是因为JS从上到下阅读,它会在您点击并触发事件之前读取您的延迟。 Therefore, even when you click the delay is being run causing all animation to pause. 因此,即使您单击正在运行的延迟,也会导致所有动画暂停。

This would be an ideal use for jQuery 1.5's new Deferred objects: 这将是jQuery 1.5的新Deferred对象的理想用法:

// 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/ 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. 请注意,如果按下按钮,计时器仍会触发,则无关紧要 - 忽略对def.resolve()的第二次调用。

I fount it the best workaround suggested by Oscar Godson, I somehow added this to it: 我认为它是Oscar Godson建议的最好的解决方法,我不知怎的把它添加到它:

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/ 你应该把它改成setTimeout: http//jsfiddle.net/VRYBk/3/

(in the jsfiddle link) I removed your delay line and replaced it with a standard setTimeout like: (在jsfiddle链接中)我删除了你的延迟线,并将其替换为标准的setTimeout,如:

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

By Oscar Godson, 奥斯卡龙顿,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM