[读码时间] 倒计时时钟
说明:代码取自网络,注释为笔者学习时添加!
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>倒计时时钟</title> <style> body,div{/*清除内外边距*/ margin:0; padding:0; } body{ color:#fff;/*白色*/ font:16px/1.5 \5fae\8f6f\96c5\9ed1;/*行高24*/ } #countdown{ width:300px; text-align:center;/*居中*/ background:#1a1a1a;/*黑色*/ margin:10px auto;/*左右置中*/ padding:20px 0; } input{ border:0; width:283px; height:50px; cursor:pointer; margin-top:20px; background:url(img/btn-1.png) no-repeat; } input.cancel{ background-position:0 -50px;/*定位背景图片位置,水平方向不变,向上移动50px*/ } span{ color:#000;/*黑色*/ width:80px; line-height:2;/*即2X16=32px*/ background:#fbfbfb;/*白色*/ border:2px solid #b4b4b4;/*灰色*/ margin:0 10px; padding:0 10px; } </style> <script> var oCountDown = document.getElementById("countdown");//获取div引用 var aInput = oCountDown.getElementsByTagName("input")[0];//获取input集合中的第一个元素引用 var timer = null;//定义计时器,设置为null,表示稍后会引用一个对象 aInput.onclick = function () {//注册click事件 this.className == "" ? (timer = setInterval(updateTime, 1000), updateTime()) : (clearInterval(timer));//三元操作法 this.className = this.className == '' ? "cancel" : ''; }; function format(a) { return a.toString().replace(/^(\d)$/, '0$1');//正则中有一个捕获组,会捕获单个数字,再用前缀0+捕获组替换。此处$1表示捕获组 } function updateTime() { var aSpan = oCountDown.getElementsByTagName("span");//获取所有span元素引用 var oRemain = aSpan[0].innerHTML.replace(/^0/, '') * 60 + parseInt(aSpan[1].innerHTML.replace(/^0/, '')); if (oRemain <= 0) { clearInterval(timer); return; } oRemain--; aSpan[0].innerHTML = format(parseInt(oRemain / 60)); oRemain %= 60; aSpan[1].innerHTML = format(parseInt(oRemain)); } </script> </head> <body> <!--外部div包裹2个span和1个input--> <div id="countdown"> <span>01</span>分钟<span>40</span>秒 <input type="button" value="" /> </div> </body> </html>