JavaScript 原生 小案例 秒殺時鐘倒數計時

Winter_Wang發表於2019-01-19

功能介紹:

1.時/分/秒倒數計時直至為零

JavaScript 原生 小案例 秒殺時鐘倒數計時

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8" />
      <title>倒數計時</title>
      <style type="text/css">
         *{
            margin:0; 
            padding:0;
            }
            span{
                display: inline-block;
                width: 60px;
                height: 60px;
                border-radius: 50%;
                background: black;
                color: white;
                font-size: 30px;
                text-align: center;
                line-height: 60px;
            }
            i{
                font-style: normal;
                font-size: 20px;
            }
      </style>
   </head>
   <body>
        <span id="hs">1</span>
        <i>:</i>
        <span id="ms">59</span>
        <i>:</i>
        <span id="ss">47</span>
   </body>
</html>
<script type="text/javascript">
//倒數計時
var count = 1;
var Counter;
function countDown(){ //呼叫
   Counter = setInterval(f,1000);
}  
countDown(); //自執行
//倒數計時
function f(){
   var hs = Number(document.getElementById("hs").innerHTML);
   var ms = Number(document.getElementById("ms").innerHTML);
   var ss = Number(document.getElementById("ss").innerHTML);
   if(hs==0&&ms==0&&ss==0||ss>60||ms>60||hs>24){
   var hs = document.getElementById("hs").innerHTML = "00";
   var ms = document.getElementById("ms").innerHTML = "00";
   var ss = document.getElementById("ss").innerHTML = "00";
   clearInterval(Counter);
   console.log(count);
   return;
}
   if(ss>0){
      ss--;
      document.getElementById("ss").innerHTML = ss;
      count++;
   }
   if(ss==0){
      if(ms>0){
         ms--;
         document.getElementById("ms").innerHTML = ms;
         document.getElementById("ss").innerHTML = 59;
      }
      
   }
   if(ms==0){
      if(hs>0){
         hs--;
         document.getElementById("hs").innerHTML = hs;
         document.getElementById("ms").innerHTML = 59;
      }
      
   }
}
   
</script>複製程式碼


相關文章