最近经常碰到页面活动倒计时的效果,于是写了个js倒计时的方法,独立出来成js文件,以后用到直接引用Common.js文件就可以了。很简单的js,记一下:
Common.js文件:
var CountDown = { "LeftTime": function (t) { //t参数格式 : 2015/2/11 10:08:51 var dt = new Date(t); var now = new Date(); var disTime = dt - now; if (disTime <= 0) { return 0; } var days = parseInt(disTime / (1000 * 3600 * 24)); var leftDay = parseInt(disTime % (1000 * 3600 * 24)); var hours = parseInt(leftDay / (1000 * 3600)); var leftHour = parseInt(leftDay % (1000 * 3600)); var minutes = parseInt(leftHour / (1000 * 60)); var leftMinute = parseInt(leftHour % (1000 * 60)); var seconds = parseInt(leftMinute / (1000)); var showDay = (days < 10) ? ('0' + days.toString()) : days.toString(); var showHour = (hours < 10) ? ('0' + hours.toString()) : hours.toString(); var showMinute = (minutes < 10) ? ('0' + minutes.toString()) : minutes.toString(); var showSecond = (seconds < 10) ? ('0' + seconds.toString()) : seconds.toString(); return showDay + "|" + showHour + "|" + showMinute + "|" + showSecond; }};
下面是不能实现倒计时的:
var CountDown = { "now": new Date(), // CountDown对象创建的时候,now成员变量只赋一次值 "LeftTime": function (t) { //t参数格式 : 2015/2/11 10:08:51 var dt = new Date(t); var now = this.now; // 获取的now属性的值是不变的,所以倒计时不会真正的倒计时 var disTime = dt - now; if (disTime <= 0) { return 0; } var days = parseInt(disTime / (1000 * 3600 * 24)); var leftDay = parseInt(disTime % (1000 * 3600 * 24)); var hours = parseInt(leftDay / (1000 * 3600)); var leftHour = parseInt(leftDay % (1000 * 3600)); var minutes = parseInt(leftHour / (1000 * 60)); var leftMinute = parseInt(leftHour % (1000 * 60)); var seconds = parseInt(leftMinute / (1000)); var showDay = (days < 10) ? ('0' + days.toString()) : days.toString(); var showHour = (hours < 10) ? ('0' + hours.toString()) : hours.toString(); var showMinute = (minutes < 10) ? ('0' + minutes.toString()) : minutes.toString(); var showSecond = (seconds < 10) ? ('0' + seconds.toString()) : seconds.toString(); return showDay + "|" + showHour + "|" + showMinute + "|" + showSecond; }};
使用的页面:
Index
在使用的页面使用计时器,就可以实现页面倒计时效果了。
Index
=============================================================================================
附加js面向对象知识:
//第1种写法 function Circle(r) { this.r = r; } Circle.PI = 3.14159; Circle.prototype.area = function() { return Circle.PI * this.r * this.r; } var c = new Circle(1.0); alert(c.area());
//第2种写法 var Circle = function() { var obj = new Object(); obj.PI = 3.14159; obj.area = function( r ) { return this.PI * r * r; } return obj; } var c = new Circle(); alert( c.area( 1.0 ) );
//第3种写法 var Circle = new Object(); Circle.PI = 3.14159; Circle.Area = function( r ) { return this.PI * r * r; } alert( Circle.Area( 1.0 ) );
//第4种写法 var Circle={ "PI":3.14159, "area":function(r){ return this.PI * r * r; } }; alert( Circle.area(1.0) );
//第5种写法 var Circle = new Function("this.PI = 3.14159;this.area = function( r ) {return r*r*this.PI;}"); alert( (new Circle()).area(1.0) );
特别是最后两种,经常见到。