码迷,mamicode.com
首页 > 其他好文 > 详细

2016-06-02 定时器 倒计时

时间:2016-06-03 01:11:19      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

1.未做封装的代码很是混乱

技术分享

    <style>
        input{width: 300px;height:20px;margin: 10px}
        #btn{width: 150px;height: 30px;margin-left: 65px}
    </style>

    <script>
      window.onload=function(){
          var inputs = document.getElementsByTagName(‘input‘);
          var timer=null;
          var seconds=null;
          var currentDate=null;
          var str=‘‘;
          var targetDate = new Date(inputs[0].value);//目标时间 固定不变的
          inputs[2].onclick=function(){
              clearInterval(timer);
              timer =setInterval(function(){
                  if(seconds>=0){
                      currentDate =new Date();//当前时间
                      seconds = Math.floor((targetDate-currentDate)/1000);//毫秒转换成s
                      str=Math.floor(seconds/86400)+‘天‘+Math.floor(seconds%86400/3600)+‘时‘+Math.floor(seconds%86400%3600/60)+‘分‘+seconds%60+‘ 秒‘;
                      inputs[1].value=str;
                  }else{
                      clearInterval(timer);
                  }

              },1000);
          }
      }
    </script>
</head>
<body>&nbsp;离:<input type="text" value="June 7,2016 00:00:00"><br>
还剩下:<input type="text"><br>
<input id="btn" type="button" value="开始倒计">
</body>

2.封装后的代码,更快更好

    <script>
      window.onload=function(){
          var inputs = document.getElementsByTagName(‘input‘);
          var timer=null;
          var delta=null;
          var currentDate=null;
          var str=‘‘;
          var targetDate = new Date(inputs[0].value);//目标时间 固定不变的
          inputs[2].onclick=function(){
              firstGet();//否则页面出现卡顿,这个是上来就显示时间信息到input框中

              clearInterval(timer);
              timer =setInterval(firstGet,1000);
              function firstGet(){
                  if(delta>=0){
                      currentDate =new Date();//当前时间
                      delta =targetDate-currentDate;
                      str=getDayHourMinSecondByMs(delta);
                      inputs[1].value=str;
                  }else{
                      clearInterval(timer);
                  }
              }

          }
      }
        function getDayHourMinSecondByMs(ms){
           var  seconds = Math.floor(ms/1000);//毫秒转换成s
            return Math.floor(seconds/86400)+‘天‘+Math.floor(seconds%86400/3600)+‘时‘+Math.floor(seconds%86400%3600/60)+‘分‘+seconds%60+‘ 秒‘;
      }
    </script>

 

2016-06-02 定时器 倒计时

标签:

原文地址:http://www.cnblogs.com/bravolove/p/5554893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!