2015-02-05 77 views
0

我是一個JavaScript的新手,我不知道如何在點擊鏈接後開始倒計時。 解釋我已經做了我的意思的簡單版本。 這是我的HTML:點擊一個鏈接後啓動倒數計時器

<!DOCTYPE html> 
<html> 
<head> 
    <link rel="stylesheet" type="text/css" 
      href="style.css" /> 
    <script type="text/javascript" 
      src="module.js"></script> 

</head> 
<body> 

<a href="http://www.google.com" title="google.com" target="_blank">google.com</a> 

<div id="countdown" class="timer"> 

    </div>  

</body> 
</html> 

,這是倒計時腳本:

function setCookie(cname,cvalue,exdays) 
{ 
var d = new Date(); 
d.setTime(d.getTime()+(exdays*24*60*60*1000)); 
var expires = "expires="+d.toGMTString(); 
document.cookie = cname + "=" + cvalue + "; " + expires; 
} 
function getCookie(cname) 
{ 
var name = cname + "="; 
var ca = document.cookie.split(';'); 
for(var i=0; i<ca.length; i++) 
    { 
    var c = ca[i].trim(); 
    if (c.indexOf(name)==0) return c.substring(name.length,c.length); 
    } 
return ""; 
} 

//check existing cookie 
cook=getCookie("my_cookie"); 

if(cook==""){ 
    //cookie not found, so set seconds=60 
    var seconds = 120; 
}else{ 
    seconds = cook; 
    console.log(cook); 
} 

function secondPassed() { 
    var minutes = Math.round((seconds - 30)/60); 
    var remainingSeconds = seconds % 60; 
    if (remainingSeconds < 10) { 
     remainingSeconds = "0" + remainingSeconds; 
    } 
    //store seconds to cookie 
    setCookie("my_cookie",seconds,5); //here 5 is expiry days 

    document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds; 
    if (seconds == 0) { 
     clearInterval(countdownTimer); 
     document.getElementById('countdown').innerHTML = "Click again"; 
    } else {  
     seconds--; 
    } 
} 

var countdownTimer = setInterval(secondPassed, 1000); 

是有一些英雄誰可以幫我嗎?我希望答案很簡單,但我無法弄清楚......

在此先感謝!

回答

1

喜伯特 - 揚的Groeneveld,

請找我下面給出的代碼。希望你能得到你的解決方案。

var minutes = 59; var seconds = 59;

function setCustomTimer() 
    { 
    setInterval(showtimer, 1000); 
    return false; 
    } 

    function showtimer() { 
    if(seconds == 00) 
    { 
     seconds = 60; 
     minutes--; 
    } 
    seconds--; 

    document.getElementById('countdown').innerHTML = minutes + ":" + seconds; 
    } 
</script> </head> <body> 
<a href="javascript:void(0);" onClick="setCustomTimer(60,59)" title="google.com" >google.com</a> 
<div id="countdown" class="timer"></div> </body> </html> 

如果您認爲您需要更多請讓我知道。

Regards,Vimal