0

我制作了一个倒数计时器并使用 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 嵌入任何额外的文本。

PS谁能告诉我如何设置新的倒计时日期?

4

1 回答 1

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);

​<a href="http://jsfiddle.net/NfLAB/" rel="nofollow">演示

编辑-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/

于 2012-04-06T21:40:12.933 回答