2016-04-27 89 views
3

我在使用sweetalert消息显示倒计时时遇到问题。点击后,我使用“带自动关闭计时器的消息”。我希望倒计时在消息中,用户可以看到倒计时。甜蜜的警惕。在警示框中显示倒计时

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

我不认为这是可能不改变库。也许[这个答案类似的问题](http://stackoverflow.com/questions/357188​​99/countdown-in-setinterval-function-with-sweet-alert-plugin)可以为你工作。 – michaPau

+1

看到我的答案。你会发现完整的解决方案(: –

回答

12

这是不可能与SweetAlert做。它不支持在UI上计数。但绝不说:-)

我准备了一些小技巧,它可以帮助你做到这一点。只需将以下代码添加到您的应用程序中,即可看到实时计数机制。并且不要忘记添加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); 

结果:

enter image description here

+1

WOW hack进展得非常好,非常感谢!它正在做我想要的东西...... :) –

+1

这真是太神奇了。简单的解决方案,但真的很聪明。不会自己拿出来,但很容易定制和理解。 +1! –

3

这里是更好的解决方案

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); 
    } 
})(); 
+0

快速和酷... thx – NoBody