点击或延迟后的jQuery Fadeout [英] jQuery Fadeout on Click or after delay

查看:96
本文介绍了点击或延迟后的jQuery Fadeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在网站上显示一个消息框。我希望能够在点击或X秒后淡出。问题是 delay()函数取代了 click()函数,即使你这样做也是如此点击关闭你仍然需要等待时间。

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 takes the place over the click() function making it so even if you click close you still have to wait the time.

这是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");

})

我还设置了一个简单的jsfiddle。要查看问题,请注释延迟行 http://jsfiddle.net/BandonRandon/VRYBk/1/

I also set up a simple jsfiddle. To see the problem comment out the delay line http://jsfiddle.net/BandonRandon/VRYBk/1/

推荐答案

您应该将其更改为 setTimeout
http://jsfiddle.net/VRYBk/3/

(在jsfiddle链接中)
我删除了你的延迟线并将其替换为标准的 setTimeout ,如:

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

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

作为一个原因的说明,是因为JS是从上到下阅读的,它会在之前读取你的延迟单击并触发事件。因此,即使您单击正在运行的延迟,导致所有动画暂停。

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.

这篇关于点击或延迟后的jQuery Fadeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆