0

我有一个需要设置的永久倒数计时器,但我正在努力如何正确地做到这一点。

我正在使用一个名为 coutdown 的插件,可以在这里找到:

http://www.littlewebthings.com/projects/countdown/

所以到目前为止我的设置涉及以下代码:

$(document).ready(function() {
    $('#countdown_contain').countDown({
        targetDate: {
            'day':      23,
            'month':    6,
            'year':     2013,
            'hour':     12,
            'min':      0,
            'sec':      0
        },
        omitWeeks: true
    });
});

所以这是倒计时到 2013 年 6 月 23 日星期日。当它变为零时,我需要它重置,然后开始倒计时到两周后的同一时间。所以基本上我需要一个星期天中午的两周倒计时。

我的想法是每次页面加载时对 php 脚本进行 ajax 调用,以查看与下一个倒计时日期相比我们所处的位置,然后将响应填充到 JS 变量中,这些变量将成为插件使用的信息。也许这太过分了?

我将如何构建我的 php 或 javascript 来实现我的目标?

4

2 回答 2

3

而不是 ajax,我会创建一个 javascript 函数来计算下一个有效日期,并使用它来播种计数器时间。这样,就没有额外的服务器交互。

至于自动重置,请使用onComplete事件重新设置控件的种子。


要动态构建 targetDate 结构,我会使用moment.js做这样的事情。请注意,这是我在工作中“不吸烟者的戒烟”期间将其编码为理论的,因此未经测试。请编辑,如果它不能 100% 工作,请不要投票。

function getTargetDate() {
     // initialize the static stuff...
     var retval = { 'hour':12,'min':0,'sec':0 }
     // good news! using Moment.js in the USA, Sunday is considered first day of week
     // so all we have to do is calculate the correct week number...
     var currentWeekOfYear = moment().week(); 
     // assume that we're targeting odd weeks, so 
     //  if it's odd, add 2, if it's even, add 1
     var nextTargetWeek = currentWeekOfYear;
     if( currentWeekOfYear % 2 == 0) {
         nextTargetWeek += 1;
     } else {
         nextTargetWeek += 2;
     }

     var nextTarget = moment().week(nextTargetWeek);

     // moment retains the current day, so we need to set it to sunday.
     nextTarget = nextTarget.day(0);

     // now, enrich the return value
     retval.day = nextTarget.date();
     retval.month = nextTarget.month();
     retval.year = nextTarget.year();

     return retval;
}
于 2013-06-12T18:45:42.887 回答
1

这不是一个确切的答案,但它应该让你走上正确的轨道。

您可以将变量直接回显到您的 javascript 文件中。

$(document).ready(function() {
$('#countdown_contain').countDown({
    targetDate: {
        'day':      <?php echo(json_encode($day)); ?>,
        'month':    <?php echo(json_encode($month)); ?>,
        'year':     <?php echo(json_encode($year)); ?>,
        'hour':     <?php echo(json_encode($hour)); ?>,
        'min':      <?php echo(json_encode($min)); ?>,
        'sec':      <?php echo(json_encode($sec)); ?>
    },
    omitWeeks: true
});
});

在您的 php 脚本中,您可以使用strtotime() 来计算下一个目标日期。

于 2013-06-12T18:46:51.977 回答