用JS面向对象写的倒计时器

时间:2022-10-11 17:24:47

<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>counter</title>
<script language="javascript" type="text/JavaScript">
function Counter(nMax,nInterval)
{
this.maxTime=nMax;
this.interval=nInterval;
this.objId="timer";
this.obj=null;
this.num=this.maxTime;
this.start=function()
{
this.obj=document.getElementById(this.objId);
if(this.num>0) setTimeout("this.run()",this.interval*1000);
};
this.run=function()
{ i
f(this.num>0)
{
this.num--;
this.obj.innerHTML=this.num;
timer=setTimeout("this.run()",this.interval*1000);
}
else clearTimeout(timer);
};
this.show=function()
{
document.write("<span id="+this.objId+">"+this.num+"</span>");
this.obj=document.getElementById(this.objId); //alert(this.obj.innerHTML);
}
}
</script>
</head> 

<body onload="myCounter.start();">
<script language="JavaScript" type="text/JavaScript">
var myCounter=new Counter(10,1);
</script>
<p>现在剩下
<script language="JavaScript" type="text/JavaScript"> myCounter.show(); </script>
秒钟!</p>
</body>
</html>