日期:2014-05-16  浏览次数:20486 次

js 倒计时功能
<html>
<head>
<title>2011倒计时</title>
</head>
<body>
<script type="text/javascript">
window.onload = function(){
    var curDate = new Date();//当前时间
    var expireDate = new Date(2012,0,1);//到期时间
    var milSecond = expireDate.getTime() - curDate.getTime();
    var totalSeconds = removeDecimal(milSecond/1000);//剩余秒(应该用服务器时间替代)
    timeGo(totalSeconds);
}
function timeGo(totalSeconds){
    setInterval(function(){
      totalSeconds--;
      calculateTime(totalSeconds);
    },1000);
}
function calculateTime(totalSeconds){
  if (totalSeconds > 0) {
    var leftDays = removeDecimal(totalSeconds/60/60/24);//剩余天数
    var seconds = totalSeconds%(60*60*24);
    var leftHours = removeDecimal(seconds/60/60);//剩余小时
    var leftMinutes = removeDecimal(seconds/60%60);//剩余分
    var leftSeconds = removeDecimal(seconds%60);//剩余秒

    setLeftTime(leftDays,leftHours,leftMinutes,leftSeconds);
  } else {
    document.getElementById('countDown').innerHTML='Happy new year!';
  }
}
function setLeftTime(leftDays,leftHours,leftMinutes,leftSeconds){
  document.getElementById('leftDay').innerHTML=leftDays;
  document.getElementById('leftHour').innerHTML=leftHours;
  document.getElementById('leftMinute').innerHTML=leftMinutes;
  document.getElementById('leftSecond').innerHTML=leftSeconds;
}
//去除小数
function removeDecimal(number){
  return Math.floor(number);
}
</script>
<div id="countDown">
  2011年倒计时:
  <span id="leftDay" style="background:red"></span>天
  <span id="leftHour"></span>小时
  <span id="leftMinute"></span>分
  <span id="leftSecond"></span>秒
</div>
</body>
</html>