JS倒计时特效

因为公司的业务是做教育的,所以页面上有关于考试时间的倒计时特效,这些考试时间都是定死的,每月都有几场,每次需要人工手动去修改,太麻烦,所以需求来了:


小二儿,上代码~

  1. // 基于 jQuery
  2. // 声明“类”,传入2个值:时间数组和Dom对象
  3. function CountDown(times, elements) {
  4. this.times = times;
  5. this.eleDay = elements.eleDay;
  6. this.eleHour = elements.eleHour;
  7. this.eleMin = elements.eleMin;
  8. this.eleSec = elements.eleSec;
  9. }
  10. CountDown.prototype = {
  11. // 将数组中的格式时间转换为时间戳,返回新的数组
  12. timeStamp: function(arr) {
  13. var newArr = [];
  14. for (var i = 0; i < arr.length; i++) {
  15. var time = Date.parse(new Date(arr[i]));
  16. newArr[i] = time / 1e3;
  17. }
  18. return newArr;
  19. },
  20. // 获取当前时间,返回时间戳
  21. nowTime: function() {
  22. var nowTime = Date.parse(new Date());
  23. return nowTime = nowTime / 1e3;
  24. },
  25. // 计算时间差,返回差值时间戳
  26. timeDiff: function() {
  27. var timeDiff,
  28. newDate = new Date(),
  29. newArr = this.timeStamp(this.times);
  30. for (var i = 0; i < newArr.length; i++) {
  31. if (newArr[i] > this.nowTime()) {
  32. timeDiff = newArr[i] - this.nowTime();
  33. return timeDiff;
  34. }
  35. }
  36. },
  37. // 将差值时间戳格式化,替换元素文本,开始倒计时
  38. format: function() {
  39. var that = this,
  40. timeDiff = this.timeDiff(),
  41. timeFormat = setInterval(function() {
  42. if (timeDiff > 0) {
  43. timeDiff -= 1;
  44. var dayTxt = Math.floor((timeDiff / 3600) / 24),
  45. hourTxt = Math.floor((timeDiff / 3600) % 24),
  46. minTxt = Math.floor((timeDiff / 60) % 60),
  47. secTxt = Math.floor(timeDiff % 60);
  48. that.eleDay && $(that.eleDay).text(dayTxt < 10 ? "0" + dayTxt : dayTxt);//计算天
  49. $(that.eleHour).text(hourTxt < 10 ? "0" + hourTxt : hourTxt);//计算小时
  50. $(that.eleMin).text(minTxt < 10 ? "0" + minTxt : minTxt);//计算分
  51. $(that.eleSec).text(secTxt < 10 ? "0" + secTxt : secTxt);// 计算秒
  52. } else {
  53. clearInterval(timeFormat);
  54. }
  55. }, 1e3);
  56. },
  57. init: function() {
  58. return this.format();
  59. }
  60. };
  61. var timeArr = ["2015/12/12 00:00:00", "2015/12/13 00:00:00", "2015/12/19 00:00:00"],
  62. elements = {
  63. eleDay: ".demo .day",
  64. eleHour: ".demo .hour",
  65. eleMin: ".demo .minute",
  66. eleSec: ".demo .second"
  67. };
  68. var countDowns = new CountDown(timeArr, elements);
  69. countDowns.init();
  1. <div class="demo">
  2. <span class="day"></span>
  3. <span class="hour"></span>小时
  4. <span class="minute"></span>分钟
  5. <span class="second"></span>
  6. </div>
发表评论
* 昵称
* Email
* 网址
* 评论