js倒计时简单实现方法

本文实例讲述了js倒计时简单实现方法的代码,分享给大家供大家参考,具体如下:

function timeDown(second) {
  var month = '', day = '', hour = '', minute = '';
  if (second >= 86400 * 30) {
   month = Math.floor(second / (86400 * 30)) + '月';
   second = second % (86400 * 30);
  }
  if (second >= 86400) {
   day = Math.floor(second / 86400) + '天';
   second = second % (86400);
  }
  if (second >= 3600) {
   hour = Math.floor(second / 3600) + '小时';
   second = second % 3600;
  }
  if (second >= 60) {
   minute = Math.floor(second / 60) + '分';
   second = second % 60;
  }
  if (second > 0) {
   second = second ? second + '秒' : '';
  }
  return month + day + hour + minute + second;
 }

如果想显示倒计时效果,可以使用如下代码调用:

<!-- 引入jquery -->
<script>
 $(function () {
  var second = 10000;
  $('.remain_time').html(timeDown(second));
  setInterval(function () {
   second--;
   $('.remain_time').html(timeDown(second));
  }, 1000);
 })
</script>
<span class="remain_time"></span>

 jquery插件形式:

   $.fn.timeDown = function (opt) {
    var second = opt.second;
    var tip = '已过期';
    var $this = this;
    self._timeDown = function (second) {
     var month = '', day = '', hour = '', minute = '';
     if (second >= 86400 * 30) {
      month = Math.floor(second / (86400 * 30)) + '月';
      second = second % (86400 * 30);
     }
     if (second >= 86400) {
      day = Math.floor(second / 86400) + '天';
      second = second % (86400);
     }
     if (second >= 3600) {
      hour = Math.floor(second / 3600) + '小时';
      second = second % 3600;
     }
     if (second >= 60) {
      minute = Math.floor(second / 60) + '分';
      second = second % 60;
     }
     if (second > 0) {
      second = second ? second + '秒' : '';
     } else {
      return tip;
     }
     return month + day + hour + minute + second;
    };
    $this.html(self._timeDown(second));
    setInterval(function () {
     second--;
     $this.html(self._timeDown(second));
    }, 1000)
   };
// 使用方式
$('.remain_time').timeDown({second:1000,tip:'已过期'})

希望本文所述对大家JavaScript程序设计有所帮助。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。