简体   繁体   English

JQuery弹出消息

[英]JQuery Pop up message

I am trying to make a custom pop up message, that appears, displays to the user for 5 seconds and then fades out. 我试图制作一个自定义弹出消息,显示,向用户显示5秒钟然后淡出。 This works fine BUT if the use triggers the event multiple times and the time out is already running the message quickly disappears. 这工作正常但是如果使用多次触发事件并且超时已经运行,则消息很快消失。

My function so far... 我的功能到目前为止......

function showMessage(message) {
    $(".messageText").text(message);

    $(".message").fadeIn("slow");    

    closeBox = function(){
        $(".message").fadeOut("slow");    
    }

    clearInterval(closeBox);
    setInterval(closeBox, 5000);
}

Many thanks 非常感谢

Try this: 尝试这个:

var interval;

function showMessage(message) {
    $(".messageText").text(message);

    $(".message").fadeIn("slow");
    if(interval){ // If a interval is set.
        clearInterval(interval);
    }
    interval = setInterval(closeBox, 5000);
}

function closeBox(){
    $(".message").fadeOut("slow");    
}

You need to assign the return of setInterval to a variable. 您需要将setInterval的返回值分配给变量。 This handle can be used to end the interval with clearinterval . 此句柄可用于以clearinterval结束间隔。 (You can't clear a interval by function, only by interval handle) (您无法按功能清除间隔,仅通过间隔句柄清除)

Also, I pulled the closeBox function out of the showMessage function, it's not necessary to declare it every time showMessage is called. 另外,我把closeBox功能出的showMessage功能,它没有必要每次都宣称它showMessage被调用。

What about using jQuery delay? 使用jQuery延迟怎么样?

Sample: 样品:

$("#container").fadeIn().delay(amoutOfTimeInMiliseconds).fadeOut();

Your function: 你的功能:

function showMessage(message) {
    $(".messageText").text(message);

    $(".message").fadeIn("slow").delay(5000).fadeOut("slow");    
}

It should work... Regards. 它应该工作......问候。

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

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