简体   繁体   English

甜蜜的警觉。 在警告框中显示倒计时

[英]Sweet alert. Display countdown in alert box

I have an issue with displaying the countdown in sweetalert message. 我在sweetalert消息中显示倒计时时遇到问题。 After click i use the "A message with auto close timer". 点击后我使用“带自动关闭计时器的消息”。 I want that countdown to be in the message and user can see the countdown. 我希望倒计时在消息中,用户可以看到倒计时。

swal({  
    title: "Please w8 !",
    text: "Data loading...",
    timer: 10000,
    showConfirmButton: false 
});

It is impossible to do with SweetAlert. SweetAlert是不可能的。 It doesn't support counting on UI. 它不支持对UI进行计数。 But never say never :-) 但永远不要说永远:-)

I have prepared a little hack, which can help you to do that. 我准备了一个小黑客,它可以帮助你做到这一点。 Just add the code below to your application, and you will see live counting mechanism. 只需将下面的代码添加到您的应用程序中,您就会看到实时计数机制。 And don't forget to add jQuery too. 并且不要忘记添加jQuery。

var
    closeInSeconds = 5,
    displayText = "I will close in #1 seconds.",
    timer;

swal({
    title: "Auto close alert!",   
    text: displayText.replace(/#1/, closeInSeconds),   
    timer: closeInSeconds * 1000,   
    showConfirmButton: false 
});

timer = setInterval(function() {

    closeInSeconds--;

    if (closeInSeconds < 0) {

        clearInterval(timer);
    }

    $('.sweet-alert > p').text(displayText.replace(/#1/, closeInSeconds));

}, 1000);

Result: 结果:

在此输入图像描述

Here is better solution 这是更好的解决方案

var timer = 10, // timer in seconds
    isTimerStarted = false;

(function customSwal() {
    swal({  
        title: "Please w8 !",
        text: "Data loading..." + timer,
        timer: !isTimerStarted ? timer * 1000 : undefined,
        showConfirmButton: false
    });
    isTimerStarted = true;
    if(timer) {
        timer--;
        setTimeout(customSwal, 1000);
    }
})();

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

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