一、用js setInterval 實現,每間隔一秒調用一次倒計時函數,在函數裏面設置爲0 時,取消定時器javascript
<body> 倒計時<span id="time"></span> <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script> <script> $(document).ready(function(){ var i=9; var interval=setInterval(function(){ $("#time").html(i); i--; if(i<0){ clearInterval(interval); }; },1000); }); //總結:$("#time").html(i); 爲元素賦值 </script> </body>
二、用 js setTimeout 實現,原理是間隔一秒調用自身,直到倒計時爲0時,處理其餘業務邏輯html
<button id="btn" onclick="settime(this)">點擊</button> <script type="text/javascript"> function settime(val) { if (countdown == 0) { val.removeAttribute("disabled"); val.innerHTML="免費獲取驗證碼"; countdown = 60; } else { val.setAttribute("disabled", true); val.innerHTML="從新發送(" + countdown + ")"; countdown--; } setTimeout(function() {settime(val)},1000) } </script>
三、用jquery setInterval 實現倒計時java
<div class="state state1"> <span id="content" class="orange">10 </span>秒後從新關閉 </div> <div class="outbuttonDiv"> <button class="btn-primary" id="buttonClose" >閥門關閉</button> </div> <script type="text/javascript"> $(function () { $('#buttonClose').click(function () { var count = 10; var countdown = setInterval(CountDown, 1000); function CountDown() { $("#buttonClose").attr("disabled", true); $("#content").html(count+" "); if (count == 0) { $(".state1").addClass("green").html("關閉成功"); //$(".state1").addClass("red").html("關閉失敗"); //$(".state1").addClass("green"); //$("#buttonClose").removeAttr("disabled"); clearInterval(countdown); } count--; } }) }) </script>
四、用jquery setTimeout 實現倒計時jquery
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標題文檔</title> <script type="text/javascript" src="js/jquery.js"></script> </head> <body> <input type="button" id="btn" value="免費獲取驗證碼" /> <span id="content">10</span> <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> $(function() { $("#btn").click(function(){ var countdown = 10; setTimeout( function settime() { if (countdown < 0) { clearTimeout(a) $("#content").html("finished"); //countdown = 60; } else { $("#content").html(countdown); countdown--; } var a = setTimeout(settime, 1000) },0) }) }) </script> </body>