首頁  >  文章  >  web前端  >  js倒數簡單實作方法_javascript技巧

js倒數簡單實作方法_javascript技巧

WBOY
WBOY原創
2016-05-16 15:25:211619瀏覽

本文實例講述了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 &#63; 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程式設計有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn