使用JavaScript实现秒表的倒计时。
我设置的是五分钟倒计时,倒计时时间是可以自己随意设置的。
效果图
代码演示
<!DOCTYPE html>
<html><head><meta charset="utf-8" /><title></title></head><style>#timer{width: 400px;height: 120px;border: 1px solid red;text-align: center;background-color: cadetblue;}#one{width: 50px;height: 30px;margin-top: 10px;margin-left: 70px;float: left;font-size: 20px;border-radius: 10px;text-align: center;color: greenyellow;background-color: darkcyan;}.two{width: 50px;height: 30px;margin-top: 10px;margin-left: 15px;float: left;border-radius: 10px;font-size: 20px;text-align: center;color: greenyellow;background-color: darkcyan;}</style><body><!-- 5分钟倒计时 --><div id="timer"><div id="one">h</div><div class="two">min</div><div class="two">s</div><div class="two">ms</div><span id="time" style="font-size: 3em">00:05:00:00</span></div></body><script type="text/javascript">var clock=document.getElementById("time");var start = clock.innerHTML;var finish = "00:00:00:00";var time = null;run();//定义时间函数,让秒表每100ms变化一次function run() {time =setInterval("onTime()", 100);}function onTime(){if (start == finish){clearInterval(time);start="00:00:00:10";}//定义赋值var hms = new String(start).split(":");var ms = new Number(hms[3]);var s = new Number(hms[2]);var m = new Number(hms[1]);var h = new Number(hms[0]);ms -= 10;if (ms < 0){ms = 90;s -= 1;if (s < 0){s = 59;m -= 1;}if (m < 0){m = 59;h -= 1;}}//判断如果是个位数前面加0var ms = ms < 10 ? ("0" + ms) : ms;var ss = s < 10 ? ("0" + s) : s;var sm = m < 10 ? ("0" + m) : m;var sh = h < 10 ? ("0" + h) : h;start = sh + ":" + sm + ":" + ss + ":" + ms;//在次赋值clock.innerHTML = start;}</script>
</html>