单击链接后启动倒数计时器

时间:2015-02-05 19:23:05

标签: hyperlink click countdown launch

我是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 个答案:

答案 0 :(得分:1)

  

嗨Bert-Jan 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>
     

如果您认为需要更多,请告诉我。

     

问候,Vimal