js实现是倒计时功能

工作中经常用到倒计时的功能,最近在整理之前做的项目的时候,发现自己写过一个倒计时的功能的效果,这里和大家分享下!实现这个功能是用原生js写的,不需要加载额外的库文件!功能比较简单,但是可以在此基础上扩展程序,得到想要的效果!

这里附上效果图先:

效果比较简单,只是简单的加了下样式!

代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>倒计时功能</title>
    <style type="text/css">
       #box{width:300px; height:60px; background:#000;margin:0 auto;}
       #box ul{margin:0; padding:0;width:300px; height:60px; clear:both;}
       #box ul li{list-style:none; float:left;width:100px; height:60px; text-align:center; font:40px/60px 微软雅黑; color:#fff;}
       .fr{float:right;}
    </style>
</head>
<body>
  <div id="box">
      <ul>
         <li id="hourseCon">00</li>
         <li id="minuteCon">00</li>
         <li id="secondCon">00</li>
      </ul>
  </div>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
var timer;
function ShowCountDown(year,month,day,hourss) 
{
    var now = new Date()
    var endDate = new Date(year, month-1, day ,hourss);
    var leftTime=parseInt(endDate.getTime())-parseInt(now.getTime());
    if(leftTime <= 0)
    {
      leftTime = 0;
    }
    var leftsecond = parseInt(leftTime/1000);
    var hour = Math.floor(leftsecond/3600).toString(); 
    var minute = Math.floor((leftsecond-hour*3600)/60).toString();
    var second = Math.floor(leftsecond-hour*3600-minute*60).toString();
    var getHourseC = document.getElementById("hourseCon");
    var getMinuteC = document.getElementById("minuteCon");
    var getSecongC = document.getElementById("secondCon");
    getHourseC.innerHTML = (hour.length < 2) ? 0+ hour : hour;
    getMinuteC.innerHTML = (minute.length < 2) ? 0+ minute : minute;
    getSecongC.innerHTML = (second.length < 2) ? 0+ second : second;
}
//开启计时功能
//timestring 时间戳(这里传过来的是2014-9-25) hours是截止的时间(这里以小时为例)
function startCount(timestring,hours)
{
       var timef = timestring.toString();
       var ss = [];
       ss = timef.split("-");
       var year = ss[0];
       var month = ss[1];
       var day = ss[2];
       var hour = hours;
       timer = window.setInterval(function()
            {
               day = parseInt(ss[2]);
               ShowCountDown(year,month,day,hour);
               var hourhtml = document.getElementById("hourseCon").innerHTML;
               var minutehtml = document.getElementById("minuteCon").innerHTML;
               var secondhtml = document.getElementById("secondCon").innerHTML;
                //倒计时结束
                  if(hourhtml == 00 && minutehtml == 00 && secondhtml == 00)
                   {
                       window.clearInterval(timer);
                   }
            }, 1000);
    }
    startCount(2014-9-28,16);
}
</script>

上面的js做了一点简单的处理,当位数只有1位的时候会在前面自动补0!

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。