2013-04-11 50 views
-1

我剛剛開始'學習'jQuery,所以我幾乎一無所知。但是,我想要一個秒錶,顯示分鐘,秒和毫秒。我想通過按空格鍵啓動計時器,並再次按空格鍵停止計時器。有沒有人有如何做到這一點的想法?記住,我對jQuery相當陌生,所以一個好的描述會很棒。以毫秒和空格鍵作爲觸發器的jQuery秒錶

謝謝!

+0

不一個答案,但你可能會開始閱讀http:// api。 jquery.com/keydown/或http://api.jquery.com/keyup/ – apsillers 2013-04-11 15:29:26

回答

1

做到這一點是使用new Date().getTime() 檢索當前時間的方式的間隔內比較我們存儲與當前時間的初始時間:

currentTime - startTime = difference in MS

如今在MS這種差異,我們可以很容易地做一些基本的數學:

LIVE DEMO

var int, ms=0, s=0, m=0; 

function swatch(){ 

    var startTime = new Date().getTime(); 
    int = setInterval(function(){ 
     var time = new Date().getTime(); 
     var dif = time-startTime; 
     ms= dif%1000; 
     s = Math.floor(dif/1000)%60; 
     m = Math.floor(dif/1000/60)%60; 
     $('#swatch').text(m+':'+s+':'+ms); 
    },1); 

} 


$(document).on('keydown', function(e){ 
    if(e.keyCode == 32 && !int){ 
     swatch(); 
    }else{ 
    clearInterval(int); 
    int=0; 
    } 
}); 

OR THIS WAY (Read Rick's comments below)爲主導的 「0」

s = ('0'+ Math.floor(dif/1000)%60).slice(-2); 
    m = ('0'+ Math.floor(dif/1000/60)%60).slice(-2); 
+1

+1但是:$('#swatch')。text(('0'+ m).slice(-2)+': '+(' 0 '+ S).slice(-2)+':「+ MS);只是因爲它更漂亮;) – 2013-04-11 16:33:18

+0

@RickCalder在演示中實現了很好的使用'.slice()'。 – 2013-04-11 16:47:55

+0

不錯,在我看到你的答案之前,我正在擺弄這件事,然後意識到我對js的瞭解實在太少了。<我的相對於你而言如此不雅,我沒有打擾。 – 2013-04-11 16:49:58