<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
header {
height: 500px;
width: 400px;
background-color: cyan;
margin: auto;
text-align: center;
padding-top: 40px;
}
button {
margin: 10px;
}
</style>
</head>
<body>
<header>
<div>
<span>00 </span>
<span>00 </span>
<span>00 </span>
</div>
<div><button>开始</button></div>
<div><button>暂停</button></div>
<div><button>归零</button></div>
</header>
</body>
</html>
<script>
function add0(num) {
return num >= 10 ? num : "0" + num;
}
var start = document.querySelectorAll("button")[0];
var pause = document.querySelectorAll("button")[1];
var stop = document.querySelectorAll("button")[2];
var h = document.querySelectorAll("span")[0];
var m = document.querySelectorAll("span")[1];
var s = document.querySelectorAll("span")[2];
var num = 0;
var timer = null;
start.addEventListener("click", function () {
timer = setInterval(function () {
num++;
s.innerHTML = add0(num);
// 小时向下取整
var hour = add0(Math.floor(num / 60 / 60));
// 66 1分零6秒
// 1小时 = 60*60 = 3600s
// 3666 1小时1分6秒
// 62
var minutes = add0(Math.floor(num / 60) % 60);
var second = add0(num % 60);
h.innerHTML = hour;
m.innerHTML = minutes;
s.innerHTML = second;
}, 0);
});
</script>
计时器案例
最新推荐文章于 2023-10-14 20:25:00 发布