【问题标题】:Moment.js creating a popup at a specific timeMoment.js 在特定时间创建弹出窗口
【发布时间】:2015-03-25 22:43:31
【问题描述】:
这是我第一次使用moment.js,但我试图创建一个弹出窗口或按钮出现的时间段。因为这是我第一次使用它,所以通过文档非常不清楚如何解决这个问题:
http://momentjs.com/docs 我想到的方式是通过持续时间部分或操作
$('.button').hide();
if(moment.duration(9, 'hours')){
$('.button').show();
}
else{
$('.button').hide();
}
所以是这样的,但我不确定,我正在努力让时间从早上 9 点开始
【问题讨论】:
标签:
javascript
jquery
html
momentjs
【解决方案1】:
我设法将上述两种方法结合起来。我需要在特定的时间间隔内激活一个按钮:感谢 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);
【解决方案2】:
我最终在网站外使用了 get set 功能,所以它看起来像这样:
$('.button').hide();
if(moment().hours() >= 9 && moment().hours() <= 11){
$('.button').show();
}
else{
$('.button').hide();
}
对于momentjs来说效果很好
【解决方案3】:
要在某个时间显示按钮,比如 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
【解决方案4】:
无需使用持续时间。 moment.js 不会给你超时(持续时间只是持续时间,比如 2 小时等)所以只需使用原版的:
function showSomething(){
$('#something').show();
}
setTimeout(showSomething, 1000);
你当然也可以写:
setTimeout(showSomething, moment.duration(2, 'seconds'));
但我看不到您问题中的用例。