wtxnpw 发表于 2017-12-9 12:41:34

【JavaScript】分秒倒计时器

  一、基本目标
  在JavaScript设计一个分秒倒计时器,一旦时间完毕使button变成不可点击状态
  详细效果例如以下图。为了说明问题。调成每50毫秒也就是每0.05跳一次表,



  真正使用的时候,把window.onload=function(){...}中的setInterval("clock.move()",50);从50调成1000就可以。
  在时间用完之前,button还是能够点击的。
  时间用完之后。button就不能点击了。
  


  二、制作过程
<!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;>
<html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;>
<head>
<meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; />
<title>time remaining</title>
</head>
<!--html部分非常easy,须要被javascript控制的行内文本与提交button都被编上ID-->
<body>
剩余时间:<span id=&quot;timer&quot;></span>
<input id=&quot;go&quot; type=&quot;submit&quot; value=&quot;go&quot; />
</body>
</html>
<script>
/*主函数要使用的函数,进行声明*/
var clock=new clock();
/*指向计时器的指针*/
var timer;
window.onload=function(){
/*主函数就在每50秒调用1次clock函数中的move方法就可以*/
timer=setInterval(&quot;clock.move()&quot;,50);
}
function clock(){
/*s是clock()中的变量,非var那种全局变量,代表剩余秒数*/
this.s=140;
this.move=function(){
/*输出前先调用exchange函数进行秒到分秒的转换,由于exchange并不是在主函数window.onload使用,因此不须要进行声明*/
document.getElementById(&quot;timer&quot;).innerHTML=exchange(this.s);
/*每被调用一次。剩余秒数就自减*/
this.s=this.s-1;
/*假设时间耗尽,那么。弹窗,使button不可用,停止不停调用clock函数中的move()*/
if(this.s<0){
alert(&quot;时间到&quot;);
document.getElementById(&quot;go&quot;).disabled=true;
clearTimeout(timer);
}
}
}
function exchange(time){
/*javascript的除法是浮点除法。必须使用Math.floor取其整数部分*/
this.m=Math.floor(time/60);
/*存在取余运算*/
this.s=(time%60);
this.text=this.m+&quot;分&quot;+this.s+&quot;秒&quot;;
/*传过来的形式參数time不要使用this,而其余在本函数使用的变量则必须使用this*/
return this.text;
}
</script>
页: [1]
查看完整版本: 【JavaScript】分秒倒计时器