1.任务分析
倒计时程序,顾名思义,他就跟秒表一样,假如你设置单位时间是100秒,开始倒计时以后,会从100秒开始递减,直到时间为0那么这个程序就不再执行了,而我们可以把这个任务分析一下:
1).使用setInterval(fun,time);和clearInterval(fun,time);的方法来实现,开始,暂停,和重置。
2).需要一个数据载体做数据展示,实现数字递减的方法是用if条件句先判断是否<=0,true就clearInterval,false则数据减1
2.html代码:
<html>
<head>
<title>js倒计时程序</title>
<script language="javascript">
var timer={
intoTime:"100",
initfun:function(){
var startBut=document.getElementById("start");
var stopBut=document.getElementById("stop");
var rerestBut=document.getElementById("rerest");
_this=this;
_this.con=document.getElementById("con");
_this.con.value="100";
startBut.οnclick=function(){
_this.creatTimer = setInterval(function(){_this.confun();},1000);
};
stopBut.οnclick=function(){
clearInterval(_this.creatTimer);
};
rerestBut.οnclick=function(){
clearInterval(_this.creatTimer);
_this.con.value="100";
};
},
confun:function(){
if(this.con.value<=0){
clearInterval(this.creatTimer);
}else{
this.con.value = this.con.value-1;
}
}
}
</script>
<style>
.box{width:300px; height:300px; margin:100px auto auto; border:1px solid blue; padding:50px 20px; text-align:center;}
#start,#stop,#rerest{cursor:pointer; padding:10px 20px;}
#con{border:none; width:100%; height:50px; border:1px solid #b2b2b2; background:#f4f4f4; line-height:50px; font-size:20px; color:#2b2b2b;}
</style>
</head>
<body>
<div class="box">
<input type="text" id="con" />
<br /><br /><br />
<input id="start" type="button" value="开始" />
<input id="stop" type="button" value="暂停" />
<input id="rerest" type="button" value="重置" />
</box>
<script language="javascript">
timer.initfun();
</script>
</body>
</html>