一、活动倒计时
//将字符串格式化为时间 function parseDate(str) { var bb = document.getElementById("bb"); if (typeof str == 'string') { var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/); if (results && results.length > 3) return new Date(parseInt(results[1], 10), parseInt(results[2], 10) - 1, parseInt(results[3], 10)); results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/); if (results && results.length > 6) return new Date(parseInt(results[1], 10), (parseInt(results[2], 10) - 1), parseInt(results[3], 10), parseInt(results[4], 10), parseInt(results[5], 10), parseInt(results[6], 10)); results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,9}) *$/); if (results && results.length > 7) return new Date(parseInt(results[1], 10), parseInt(results[2], 10) - 1, parseInt(results[3], 10), parseInt(results[4], 10), parseInt(results[5], 10), parseInt(results[6], 10), parseInt(results[7], 10)); } return null; } //倒计时 deadline:截止日期,要求格式为:yyyy-MM-dd 或者 yyyy-MM-dd HH:mm:ss或者 yyyy-MM-dd HH:mm:ss.ms // divname:倒计时要显示的位置 // type:1:显示精确到分;0:显示精确到秒 // msg1、msg2:当倒计时分别不为0、为0时显示的提示信息 function ShowCountDown(deadline, divname, type, msg1, msg2) { var cc = document.getElementById(divname); var now = new Date(); var endDate = parseDate(deadline); if (endDate != null) { var leftTime = endDate.getTime() - now.getTime(); if (leftTime > 0) { var leftsecond = parseInt(leftTime / 1000); var day = Math.floor(leftsecond / (60 * 60 * 24)); var hour = Math.floor((leftsecond - day * 24 * 60 * 60) / 3600); var minute = Math.floor((leftsecond - day * 24 * 60 * 60 - hour * 3600) / 60); var second = Math.floor(leftsecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60); if (cc != null) { if (type == 1) {cc.innerHTML = msg1 + day + "天" + hour + "小时" + minute + "分";} else { cc.innerHTML = msg1 + day + "天" + hour + "小时" + minute + "分" + second + "秒"; } } } else { cc.innerHTML = msg2; } } }
使用例子:
var interval = 1000; window.setInterval(function() { ShowCountDown('2010-6-11 15:36:00', 'div1', 1,'距停止报名还有 ', '活动已结束'); }, interval);
二、按钮禁用60秒并显示倒计时
/*按钮禁用60秒,并显示倒计时*/ function disabledButton(e){ $(e).attr({"disabled":"disabled"}); //控制按钮为禁用 var second = 60; var intervalObj = setInterval(function () { $(e).val("执行中.." + "(" + second + ")"); if(second == 0){ $(e).val("提交"); $(e).removeAttr("disabled");//将按钮可用 /* 清除已设置的setInterval对象 */ clearInterval(intervalObj); } second--; }, 1000); }
<input type="button" id="btn1" value="提交" onclick="disabledButton(this)" />