js秒表计时器
用普通js实现秒表计时器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>计时器</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
margin: 50px auto;
width: 300px;
height: 400px;
background-color: aquamarine;
}
.content {
height: 100px;
text-align: center;
line-height: 100px;
font-weight: 700;
font-size: 40px;
}
.btn {
text-align: center;
}
button {
margin-top: 20px;
font-size: 50px;
}
</style>
</head>
<body>
<div id="box">
<div class="content">
<span id="hours">00</span>
<span id="minutes">00</span>
<span id="seconds">00</span>
</div>
<div class="btn">
<button id="start">开始计时</button>
<button id="pause">暂停计时</button>
<button id="end">结束计时</button>
</div>
</div>
</body>
<script>
var timer
var time = 0
function $(id) {
return document.getElementById(id)
}
var hours = $('hours'),
minutes = $('minutes'),
seconds = $('seconds'),
start = $('start'),
pause = $('pause'),
end = $('end')
//开始计时
start.onclick = function () {
this.disabled = true
pause.disabled = false
end.disabled = false
timer = setInterval(move, 1000)
}
//暂停计时
pause.onclick = function () {
this.disabled = true
start.disabled = false
end.disabled = false
clearInterval(timer)
}
//结束计时
end.onclick = function () {
this.disabled = true
pause.disabled = false
start.disabled = false
clearInterval(timer)
time = 0
timeShow()
}
function move() {
time++
// console.log(time)
timeShow()
}
function timeFormat(t) {
t = t >= 10 ? t : '0' + t
return t
}
function timeShow() {
seconds.innerText = timeFormat(time % 60) //0-59
minutes.innerHTML = timeFormat(parseInt(time / 60) % 60)
hours.innerHTML = timeFormat(parseInt(time / 60 / 60) % 24)
}
</script>
</html>