使用jQuery倒计时

时间:2011-09-25 21:28:48

标签: javascript jquery

所以,我从我的数据库中输出了这个: 00:01:53
在span标记内

<span class="jb_timer">00:01:53</span>

所以我的问题是,我怎样才能让它与jQuery倒计时?

感谢。

3 个答案:

答案 0 :(得分:4)

这可以让你开始朝着正确的方向前进:

var remaining = $("span.jb_timer").text(),
    regex = /\d{2}/g,
    matches = remaining.match(regex),
    hours = matches[0],
    minutes = matches[1],
    seconds = matches[2],
    remainingDate = new Date();

remainingDate.setHours(hours);
remainingDate.setMinutes(minutes);
remainingDate.setSeconds(seconds);

var intvl = setInterval(function () {
    var totalMs = remainingDate.getTime(),
        hours, minutes, seconds;

    remainingDate.setTime(totalMs - 1000);

    hours = remainingDate.getHours();
    minutes = remainingDate.getMinutes();
    seconds = remainingDate.getSeconds();

    if (hours === 0 && minutes === 0 && seconds === 0) {
        clearInterval(intvl);
    }

    $("span.jb_timer").text(
        (hours >= 10 ? hours : "0" + hours) + ":" +
        (minutes >= 10 ? minutes : "0" + minutes)  + ":" +
        (seconds >= 10 ? seconds : "0" + seconds));

}, 1000);

工作示例: http://jsfiddle.net/andrewwhitaker/YbLj4/

备注:

  • 首先,您必须解析span文本中的初始小时,分钟和秒数。使用简单的正则表达式执行此操作。
  • 使用setInterval设置每1000毫秒运行一次的计时器。
  • 当该计时器触发时,从该时间减去1000毫秒并适当更新span的文本。
  • 当小时,分钟和秒数达到0时,清除(取消)间隔。

答案 1 :(得分:1)

这是一个非常简单的,似乎完全符合您的要求。它没有Hanlet链接到的脚本的铃声和口哨,我认为它比安德鲁的解决方案更简单(即使有更多的代码行...我的不使用正则表达式,也不使用Date( )对象)。

http://jsfiddle.net/ct3VW/2/

function countDown(timeDiv){
    var timeStringArray = timeDiv.text().split(':');
    var timeNumberArray = [];

    //the following loop simply converts the values in timeStringArray to actual numbers
    for(var i = 0; i < 3; i++){
        timeNumberArray.push(parseInt(timeStringArray[i],10));
    }

    timeNumberArray[2]--; //decrement the seconds

    if(timeNumberArray[2] < 0 && timeNumberArray[1] > 0){
        timeNumberArray[1]--;
        timeNumberArray[2] = 59;
    }

    //this if statement won't have any effect because the sample timer doesn't have any hours at the moment
    if(timeNumberArray[1] < 0 && timeNumberArray[0] > 0){
        timeNumberArray[0]--;
        timeNumberArray[1] = 59;
    }

    var newTimeString = (timeNumberArray[0] < 10) ? '0' + timeNumberArray[0] : timeNumberArray[0];

    for(var i = 1; i < 3; i++){
        var timePart = (timeNumberArray[i] < 10) ? ':0' + timeNumberArray[i] : ':' + timeNumberArray[i];
        newTimeString += timePart;
    }

    if(timeNumberArray[2] !== 0){   //don't want to call the function again if we're at 0
        timeDiv.text(newTimeString);
        setTimeout(
            (function(){
                countDown(timeDiv)
            }),1000);
    }else{
        //here's where you could put some code that would fire once the counter reaches 0.
    }
}

$(function(){
    countDown($('div'));
});

答案 2 :(得分:0)

互联网上有大量的样本和脚本。 Maybe you will like one of these