【问题标题】:Display alert box for countdown timer显示倒数计时器的警报框
【发布时间】:2015-05-07 17:52:47
【问题描述】:

我创建了一个倒数计时器,它在 html 中显示计时器。

我也让它显示在一个警告框中。

我的问题是我只想在用户第一次访问网站时显示警报框,这样它就不会显示在每个新页面上。

我也遇到了警告框会暂停时间直到您单击确定的问题,这会使时间延迟几秒钟,具体取决于用户单击确定的速度。

我的代码如下。

function startTimer(display) {
var date = new Date();
var h17 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 17);
if(date.getHours() >= 17) {
    h17.setDate(h17.getDate()+1);
}
h17 = h17.getTime();
var diff,
    hours,
    minutes,
    seconds;

function timer() {
    diff = (((h17 - Date.now()) / 1000) | 0);

    // Setting and displaying hours, minutes, seconds
    hours = (diff / 3600) | 0;
    minutes = ((diff % 3600) / 60) | 0;
    seconds = (diff % 60) | 0;

    hours = hours < 10 ? "0" + hours : hours;
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = hours + ":" + minutes + ":" + seconds;
};
timer();
setInterval(timer, 1000);
}
window.onload = function () {
    var display = document.querySelector('#time');
    startTimer(display);
    alert(display.textContent);
};

下面的html:

<div> time left <span id="time"></span> </div>

【问题讨论】:

  • 警报(以及确认)框将始终停止您的代码并等待用户交互。您可能需要考虑在 div 或新窗口中显示您的计时器。

标签: javascript html timer alert countdown


【解决方案1】:

您可以在 JavaScript 中使用类似 dialog 的对话框,而不是使用警告框

要使用它,您需要在文档中添加 jQuery 和 jQuery UI。然后您可以使用以下代码初始化小部件:

//When the dom is ready
$(function() {
    //This variable contains the countdown interval
    var countdown;

    //Initialization of the widget
    $( "#dialog" ).dialog({
        open: function( event, ui ) {
            //When the dialog is open we start the countdown
            countdown = startTimer($(this).find('#time')[0])
        },
        close: function( event, ui ) {
            //When the dialog is closed we stop the countdown
            clearInterval(countdown);
        }
    });
});

不要忘记在您的setInterval 上添加return 以获取倒计时:

return setInterval(timer, 1000);

这是一个演示:jsFiddle

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多