2012-10-24 38 views
1

想要在點擊一個按鈕後顯示div,然後開始時間並從10計數到0。在點擊並啓動計時器後顯示div

我的問題是我不知道如何開始計數?

的javascript:

<script> 
$("button").click(function() { 
$('div#test').hide().delay(200).fadeIn('slow'); 
}); 
</script> 

按鈕:

<div id="test" style="display:none;">click</div> 

HTML:

<div id="test" style="display:none;">here you are !</div> 

回答

0

您可以使用的setTimeout()或setInterval的()得到它的工作:

下面是我如何做到了:

$(function() { 
$("button").click(function() { 
    function counter() { 
     var i = 10; 
     $("body").append('<div style="border:1px solid red;">Div Created on the Fly</div>') 
     function showDIV() { 

     if (i < 0) 
      return 
     setTimeout(showDIV, 1000); 
     $("span").text(i); 
     i--;   

    } 

    showDIV(); 
} 
counter(10); 
}); 

}); 

DEMO

+0

之後,要做到你想要的只是將div fadeIn移動到countDown函數,這很有幫助! –

+0

@Michaelroshdy:我很高興它幫助你。 – defau1t

1

可以使用setInterval計數。

var count = 10; 
var temp = setInterval(function(){ 
    if(count < 0) { 
     clearInterval(temp); 
    } 
    // show count 
    count--; 


}, 1000); 
+0

不要忘了'clearInterval'太。 –

0
var count = 15; 
var timerID = 0; 
$("button").click(function() { 
    $('div#test').hide().delay(200).fadeIn('slow', function() { 
     timerID = setInterval(function() {countDown();}, 1000); // count every 1000 ms, change this to whatever you want 
    }); 
    $("#wait").show(); // or you could fade this in if you want. Maybe that's what you intended with #test. 
}); 

function countDown() { 
    count--; 
    $("#count").text(count); 
    // do whatever you want to do with your count 
    if (count <= 0) { 
     clearInterval(timerID); 
    } 
} 

HTML:

<p id="wait" style="display:none">Please wait<span id="count">15</span> seconds...</p> 

假設你想在淡入後開始倒計數。否則,只需將該部分拉出,並在淡入淡出線之後插入setInterval,以便在首次單擊按鈕時開始倒計時。

+0

點擊按鈕後,我想要做什麼類似「Please wait 15 seconds」 –

+0

@Michaelroshdy:查看我的編輯。你需要爲你計算一個元素(並且'span'是有意義的,因爲它是內聯的),然後當'countDown()'函數觸發時,你將改變該元素中的'.text()'。 –

+0

是否測試過!,它不能正常工作,在div展示後開始!點擊1-「Please wait 15 sec」然後消失然後顯示測試div –