如何功能化倒计时?

时间:2012-04-06 21:17:12

标签: jquery html css

我制作了一个倒数计时器并使用HTML和CSS对其进行编码,但我无法使用jQuery使其正常运行。我怎样才能将这个倒计时功能化?这是我更喜欢倒计时的HTML结构:

    <div id="counter-container">
      <div class="counter-box">
        <div class="counter"><p class="counter-p">#</p></div>
        <p class="counter-box-p">days</p>
      </div>
      <div class="counter-box">
        <div class="counter"><p class="counter-p">#</p></div>
        <p class="counter-box-p">hours</p>
      </div>
      <div class="counter-box">
        <div class="counter"><p class="counter-p">#</p></div>
        <p class="counter-box-p">minutes</p>
      </div>
      <div class="counter-box">
        <div class="counter"><p class="counter-p">#</p></div>
        <p class="counter-box-p">seconds</p>
      </div>

正如您所看到的,我已经添加了几天,几小时等段落元素,因此我不想通过jQuery嵌入任何额外的文本。

P.S。谁能告诉我如何设定新的倒计时日期?

1 个答案:

答案 0 :(得分:4)

function counter(count) {
  countdown = setInterval(function(){
    var temp;
    $("p#d").html(Math.floor(count/(60*60*24)));
    temp = count%(60*60*24);
    $("p#h").html(Math.floor(temp/(60*60)));
    temp = count%(60*60);
    $("p#m").html(Math.floor(temp/(60)));
    temp = count%(60);
    $("p#s").html(temp);
    if (count == 0) {
         alert("time's up");
         clearInterval(countdown);       
    }
    count--;
  }, 1000);
}

counter(60*60*24*2);

demo

修改-1:

计数器以秒为单位获得时间。

counter(10); //10 seconds
counter(10*60) //600 seconds -> 10 minutes.
counter(10*60*60) //36000 seconds -> 600 minutes -> 10 hour

修改-2:

如果你希望它基于Date工作,你应该改变这样的功能,

function counter(futureDate) {
  var today = new Date(); // today
  count = Math.floor((futureDate-today)/1000);
  countdown = setInterval(function(){
    var temp;
    $("p#d").html(Math.floor(count/(60*60*24)));
    temp = count%(60*60*24);
    $("p#h").html(Math.floor(temp/(60*60)));
    temp = count%(60*60);
    $("p#m").html(Math.floor(temp/(60)));
    temp = count%(60);
    $("p#s").html(temp);
    if (count == 0) {
         alert("time's up");
         clearInterval(countdown);       
    }
    count--;
  }, 1000);
}

counter(new Date(2012,4,8)); // May 8, 2012 00:00:00
/* counter(new Date(2012,4,8,15,49,10)); // May 8, 2012 15:49:00 */
​

http://jsfiddle.net/NfLAB/1/