时刻.js在特定时间创建弹出窗口

Moment.js creating a popup at a specific time

本文关键字:窗口 创建 定时间 js 时刻      更新时间:2023-09-26

这是我第一次使用moment.js,但我试图为弹出窗口或按钮的出现创建一个时间段。由于这是我第一次使用它,因此通过文档非常不清楚如何做到这一点:http://momentjs.com/docs 我想到的方式是通过持续时间部分或操作

$('.button').hide();
if(moment.duration(9, 'hours')){
$('.button').show();
}
else{
$('.button').hide();
}

所以像这样的事情,但我不确定,我正在尝试得到它,以便时间应该从上午 9 点开始

无需使用持续时间。 moment.js 不会给您超时(持续时间只是 2 小时等时间的持续时间),因此只需使用原版:

function showSomething(){
   $('#something').show();
}
setTimeout(showSomething, 1000);

当然,您也可以写:

setTimeout(showSomething, moment.duration(2, 'seconds'));

但是我在您的问题中看不到用例。

我设法将上述两种方法结合起来。我需要在特定时间间隔内激活一个按钮:归功于 Chridam 和 jsg。她的解决方案:

    $('#myButton').hide();
        if(moment().hours() >= 13&& moment().hours() <= 17)
          {
            $('#myButton').show();
           }
      else if (moment().hours() >= 1 && moment().hours() <= 2)
{
   $('#myButton').show();
}
else{
   $('#myButton').hide();
}

    // Ability to refresh
    function refreshAt(hours, minutes, seconds) {
   var now = new Date();
   var then = new Date();
   if(now.getHours() > hours || (now.getHours() == hours && now.getMinutes() > minutes) || now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >=  seconds) {
           then.setDate(now.getDate() + 1);
   }
   then.setHours(hours);
   then.setMinutes(minutes);
   then.setSeconds(seconds);
   //var timeout = (then.getTime() - now.getTime());
   //setTimeout(showButton, timeout);
};
    refreshAt(13, 00, 00);
    refreshAt(17, 0, 00);
    refreshAt(1, 00, 00);
    refreshAt(2, 00, 00);

要在某个时间显示按钮,比如 11:12 小时,您可以尝试以下操作:

$('.button').hide();
function showButton(){
   $('.button').show();
};
function refreshAt(hours, minutes, seconds) {
   var now = new Date();
   var then = new Date();
   if(now.getHours() > hours || (now.getHours() == hours && now.getMinutes() > minutes) || now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >=  seconds) {
           then.setDate(now.getDate() + 1);
   }
   then.setHours(hours);
   then.setMinutes(minutes);
   then.setSeconds(seconds);
   var timeout = (then.getTime() - now.getTime());
   setTimeout(showButton, timeout);
};
refreshAt(11, 12, 00);

JSFiddle

我最终在站点外使用了 get set 函数,所以它看起来像这样:

$('.button').hide();
if(moment().hours() >= 9 && moment().hours() <= 11){
   $('.button').show();
}
else{
   $('.button').hide();
}

这对 momentjs 工作正常