<input type="button" value="启动" id="btnStart" />
<input type="button" value="复位" id="btnReset" />
<label id="lblTime">0:0:0:0</label> #javascript:
window.onload = function () {
var start = document.getElementById("btnStart")
var reset = document.getElementById("btnReset")
var time = document.getElementById("lblTime")
var h = 0, m = 0, s = 0, ms = 0, t
//开始计时
start.onclick = function () {
bvalue = start.value
if (bvalue == "启动") {
t = window.setInterval(function () {
if (ms == 100) {
s += 1
ms = 0
}
if (s == 60) {
m += 1
s = 0
}
if (m == 60) {
h += 1
m = 0
}
time.textContent = h + ":" + m + ":" + s + ":" + ms
ms++
}, 10)
start.value = "暂停"
}
else {
window.clearInterval(t)
start.value = "启动"
}
}
//复位
reset.onclick = function () {
window.clearInterval(t)
time.textContent = 0 + ":" + 0 + ":" + 0 + ":" + 0
}
}
// 开始计时function countdown() {
var remainTime = parseInt($('#count').val())
if (remainTime > 0) {
window.timeoutId = setTimeout(function() {
$('#count').val(remainTime - 1)
clearTimeout(window.timeoutId)
countdown()
}, 1000)
}
}
用JavaScript获取服务器时间,然后做页面倒计时的程序代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html charset=utf-8"/>
<title>untitled</title>
<script type="text/javascript">
get=function (id){
return document.getElementById(id)
}
if(document.all){
window.XMLHttpRequest=function(){
var get=['Microsoft.XMLHTTP','Msxml2.XMLHTTP']
for(var i=0i<get.lengthi++)
{
try{
return new ActiveXObject(get[i])
}
catch(e){}
}
}
}
webDate=function(fn){
var Htime=new XMLHttpRequest()
Htime.onreadystatechange=function(){
Htime.readyState==4&&(fn(new Date(Htime.getResponseHeader('Date'))))
}
Htime.open('HEAD', '/?_='+(-new Date)) Htime.send(null)
}
window.time=new Date()
targetTime=new Date()
time2String=function (t){
with(t)return [getFullYear(),'年' ,('0'+(getMonth()+1)).slice(-2),'月' ,('0'+getDate()).slice(-2),'日 ' ,('0'+getHours()).slice(-2),': ' ,('0'+getMinutes()).slice(-2),': ' ,('0'+getSeconds()).slice(-2)].join('')
}
int2time=function (m){
m-=(D=parseInt(m/86400000))*86400000 m-=(H=parseInt(m/3600000))*3600000 S=parseInt((m-=(M=parseInt(m/60000))*60000)/1000)
return D+'天'+H+'小时'+M+'分'+S+'秒'
}
setInterval(function (){
webDate(function (webTime){
get('web').innerHTML=time2String(time=webTime)
})
get('locale').innerHTML=time2String(new Date)
get('time').innerHTML=int2time(targetTime-time)
if ((targetTime-time)<0) {
get('time').innerHTML = 'Game Over'
} },1000)
</script>
</head>
<body>
设定时间:2015年06月18日0时0分0秒<br> 服务器时间:<span id='web'>loading...</span><br>
本地时间:<span id="locale">loading...</span><br>
倒计时时间:<span id="time">loading...</span>
<script type="text/javascript" charset="utf-8"> targetTime=new Date(2015,06,18,00,00,00) </script>
</body>
</html>
注:原理用xmlhttp来获取服务器上的时间,后台用js做倒计时显示到页面上,由于获取服务器时间这个在本地运行不一定能成功,最好是在服务器上运行!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)