系统学习JS时的一个小练习
直接上代码吧,注释写得还算详细,就不赘述了,很简单的一个练习。
<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>简易计时器</title><style>#box {width: 300px;height: 400px;margin: 100px auto;border: 1px solid #000;background-color: orange;text-align: center;}#box span {display: inline-block;margin-top: 70px;font-size: 24px;}#box button {display: block;margin: 40px auto;padding: 5px 30px;background-color: #000;color: #fff;}</style><script>function $(id) {// 获取ID标签简化return document.getElementById(id);}function doubleNum(num) {// 时分秒数字成对显示// return num >= 10 ? num : ("0" + num);return ("00" + String(num)).substr(String(num).length); // 觉得这个方法更高大上}var i = 0; // 总秒数var timer = null; // 定时器返回值var isStart = false; // 当前计数是否开始window.onload = function () {function startFunc() {// 计数开始timer = setInterval(function () {i++;$("sec").innerHTML = doubleNum(i % 60); // 秒$("min").innerHTML = doubleNum(parseInt(i / 60) % 60); // 分$("hour").innerHTML = doubleNum(parseInt(parseInt(i / 60) / 60)); // 时}, 1000)}function pauseFunc() {// 计数暂停clearInterval(timer);}$("btn").onclick = function () {// 开始/暂停的点击事件if (!isStart) {startFunc();$("btn").innerHTML = "暂停";isStart = true;} else {pauseFunc();$("btn").innerHTML = "开始";isStart = false;}}$('reset').onclick = function () {// 复位i = 0;isStart = false;clearInterval(timer);$("btn").innerHTML = "开始";$("sec").innerHTML = "00";$("min").innerHTML = "00";$("hour").innerHTML = "00";}}</script>
</head><body><div id="box"><span id="hour">00</span><span>:</span><span id="min">00</span><span>:</span><span id="sec">00</span><br><button id="btn">开始</button><button id="reset">复位</button></div>
</body></html>