2011-09-25 114 views
1

所以,我這個從我的DB輸出: 00:01:53
裏面跨度標籤倒計時的jQuery

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

所以我的問題是,我怎麼能使其與jQuery的倒計時?

謝謝。

+5

而搞什麼名堂,你試過嗎?你有沒有發現任何與谷歌,或[這裏在Stackoverflow](http://stackoverflow.com/search?q=%5Bjquery%5D+countdown)?什麼沒有用? –

+0

我試過Google和Stackoverflow,沒有找到我要找的東西。如果你看到我的意思,那麼輸出結果是'00:01:53',它應該倒計時,就像「剩餘時間」一樣。 – NoobiCake

回答

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 ms,並適當地更新span的文本。
  • 當小時,分鐘和秒數達到0時,清除(取消)間隔。
1

這是一個非常簡單的,看起來完全符合你的要求。它沒有Hanlet鏈接到的腳本的花裏胡哨,我認爲它比Andrew的解決方案簡單一些(即使有更多的代碼行...我不使用正則表達式,也不使用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')); 
});