本篇文章给大家带来的内容是关于html如何实现计数器以及时钟的功能代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
在许多的网页中,我们都会看到计数器以及时钟,那么我们怎么自己实现着种功能呢?
先说计数器,计数器的逻辑功能很简单,就是秒针每秒加一,逢60进一就可以。代码如下:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8"/>
<title></title>
</head>
<body>
<div></div>
<script>
varindex=0;
vari=0;
/**
*对时间进行预先处理,逢60进一
*/
functioncounter(){
second=index;
minute=i;
index++;
if(second==60){
second=0;
i++;
index=0;
}
if(second<10){
second="0"+second;
}
if(minute<10){
minute="0"+minute;
}
returntime=minute+":"+second;
}
/**
*将获得的时间插入到div的区域
*/
functionshow(){
vartime=counter();
document.getElementsByTagName("div")[0].innerHTML=time;
}
/**
*每秒钟获得一次时间,实现计数功能
*/
functionset(){
setInterval("show()",1000);
}
show();
set();
</script>
</body>
</html>
这样,一个简单的计数器就完成了。
时钟功能的代码:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="UTF-8">
<title></title>
<script>
/**
*向Date类中添加获取当前时间的方法
*/
Date.prototype.currentTime=function(){
varyear=this.getFullYear();
varmonth=this.getMonth()+1;
varday=this.getDate();
varweek=this.getDay();
week="星期"+"日一二三四五六".charAt(week);
month=month<10?"0"+month:month;
day=day<10?"0"+day:day;
varhour=this.getHours();
varsecond=this.getSeconds();
varminute=this.getMinutes();
hour=hour<10?"0"+hour:hour;
second=second<10?"0"+second:second;
minute=minute<10?"0"+minute:minute;
returnyear+"-"+month+"-"+day+""+week+""+hour+":"+minute+":"+second;
}
functionshowTime(){
vartime=newDate().currentTime();
document.getElementById("show").innerHTML=time;
}
functionsetTime(){
showTime();
setInterval("showTime()",1000);
}
window.onload=function(){
setTime();
}
</script>
</head>
<body>
<spanid="show"></span>
</body>
</html>
这样,时钟就完成了!


本文转载自中文网

本文转载自中文网
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html5/h54773.shtml