倒计时模块(获取的是服务器上的时间——适合购物网站的抢购模块)

时间:2022-12-16 22:01:18

JS部分

/*ajax请求服务器当前时间*/
function servertiems() {
var A=null;
try {
A
=new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e) {
try {
A
=new ActiveXObject("Microsoft.XMLHTTP")
}
catch(oc) {
A
=null
}
}
if ( !A && typeof XMLHttpRequest != "undefined" ) {
A
=new XMLHttpRequest()
}
return A
}
var NowTime;
var tm = servertiems();
var strData="auto="+new Date().toString();
tm.onreadystatechange
= callback_st;
tm.open(
"GET","http://您的服务器输出地址",false);//服务器输出格式如:{"time": "2016/4/29 11:24:11"}
tm.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
tm.send(strData);

function callback_st(){
if (tm.readyState==4 && tm.status==200){
var result = tm.responseText;
var json = eval("(" + result + ")");
NowTime
=json.time;//获取到服务器当前时间

}
}



var today=new Date(NowTime).getTime();
var now = new Date().getTime();
var diff = (now - today);

function show_date_timezj(timesxx,xid){
window.setTimeout(
function(){show_date_timezj(timesxx,xid)},20);
BirthDay
=new Date(timesxx);//设置日期
var now_fun = new Date().getTime();
var todayx=now_fun - diff;
timeold
=(BirthDay - now_fun + diff );
sectimeold
=timeold/1000;
secondsold=Math.floor(sectimeold);
msPerDay
=86400000;

//*天数
e_daysold=timeold/msPerDay;
daysold=Math.floor(e_daysold);

//*小时
e_hrsold=(e_daysold-daysold)*24;
hrsold
=Math.floor(e_hrsold);
e_minsold
=(e_hrsold-hrsold)*60;
minsold
=Math.floor((e_hrsold-hrsold)*60);
e_seconds
= (e_minsold-minsold)*60;
seconds
=Math.floor((e_minsold-minsold)*60);
ms
= e_seconds-seconds;
ms
= new String(ms)
ms
= ms.substr(2,3);

if(daysold>=0){
document.getElementById(xid).innerHTML
="<span>距离开始时间还有: <font color='#ff0000'>"+(daysold<10?'0'+daysold:daysold)+"</font>天</span>"+"<span><font color='#ff0000'>"+(hrsold<10?'0'+hrsold:hrsold)+"</font>小时</span>"+"<span><font color='#ff0000'>"+(minsold<10?'0'+minsold:minsold)+"</font>分</span>"+"<span><font color='#ff0000'>"+(seconds<10?'0'+seconds:seconds)+"</font>秒</span>"+"<span><font color='#ff0000'>"+ms+"</font><span>";
}
else{
document.getElementById(xid).innerHTML
='';
document.getElementById(xid).nextSibling.className
='';
}

}

 

HTML部分

<div>
<div id="span_k1"></div><a href="" class="no_ac">进入</a>
<div id="span_k2"></div><a href="" class="no_ac">进入</a>
<div id="span_k3"></div><a href="" class="no_ac">进入</a>
</div>

 

 JS调用

var spank1=new show_date_timezj("05/06 /2015 19:30:00","span_k1");
var spank2=new show_date_timezj("05/07 /2015 09:00:00","span_k2");
var spank3=new show_date_timezj("05/08 /2015 19:00:00","span_k3");