基于moment的倒计时
2017-03-22 16:08
337 查看
//定义一个立即执行的函数 (function () { var Ticts=function Ticts() { this.ticts = {}; }; Ticts.prototype.createTicts=function(id, dealline) { var ticts=this; var time=moment(dealline).diff(moment()); var _ticts=this.ticts[id] = { dealine: dealline , id: id , time: time , interval: setInterval(function () { var t = null; var d = null; var h = null; var m = null; var s = null; //js默认时间戳为毫秒,需要转化成秒 t = _ticts.time / 1000; d = Math.floor(t / (24 * 3600)); h = Math.floor((t - 24 * 3600 * d) / 3600); m = Math.floor((t - 24 * 3600 * d - h * 3600) / 60); s = Math.floor((t - 24 * 3600 * d - h * 3600 - m * 60)); //这里可以做一个格式化的处理,甚至做毫秒级的页面渲染,基于DOM操作,太多个倒计时一起会导致页面性能下降 document.getElementById(id).innerHTML = d + '天' + h + '小时' + m + '分钟' + s + '秒'; _ticts.time -= 1000; if (_ticts.time < 0) ticts.deleteTicts(id);//判断是否到期,到期后自动删除定时器 }, 1000) } }; Ticts.prototype.deleteTicts = function(id) { clearInterval(this.ticts[id].interval);//清楚定时器的方法,需要定时器的指针作为参数传入clearInterval delete this.ticts[id];//通过delete的方法删除对象中的属性 }; //新建一个ticts对象,放到window全局函数中,那么在html页面是(或者其他js文件)可以访问该对象 window.Ticts=new Ticts();})();
用法:html页面首先要引入moment才能使用我上面的方法<script src="//cdn.bootcss.com/moment.js/2.17.1/moment.min.js"></script>
假设HTML里要放入倒计时的地方在这里
<div id="aaa"></div>
<div id="aaa1"></div>
<div id="aaa2"></div>页面上可以写js:
Ticts.createTicts("aaa","2017-1-20 20:20:20");
Ticts.createTicts("aaa1","2017-1-22 20:20:20");
Ticts.createTicts("aaa2","2017-1-23 20:20:20");
相关文章推荐
- 利用moment为基础,基于DOM实现一个多个倒计时同时进行的js库方便使用
- 基于javascript实现的购物商城商品倒计时实例
- 基于jQuery的倒计时实现代码
- 基于jQuery+Cookie实现的防止刷新的在线考试倒计时
- 基于简单JavaScript的网页倒计时
- 基于JavaScript实现网页倒计时自动跳转代码
- 基于javascript实现精确到毫秒的倒计时限时抢购
- 基于jquery的一个倒计时demo
- jQuery基于扩展简单实现倒计时功能的方法
- 基于JS实现发送短信验证码后的倒计时功能(无视页面刷新,页面关闭不进行倒计时功能)
- 基于javascript显示当前时间以及倒计时功能
- 基于jquery的-获取短信验证码-倒计时
- C#基于TimeSpan实现倒计时效果的方法
- 贴一段基于jquery实现的倒计时功能的函数
- 基于javascript实现的购物商城商品倒计时实例
- 基于cookie实现发送短信验证码后的倒计时功能(无视页面刷新)
- 基于Javascript倒计时效果
- 基于第三方的倒计时控件
- 基于JavaScript实现网页倒计时自动跳转代码
- android 倒计时、有清除功能编辑框、popupwindow、跑马灯效果实现(基于TextView)