简单实现了一个有开始、暂停和归零的秒表
代码如下:
<!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>
* {
user-select: none;
}
#kuai {
position: absolute;
top: 40%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 130px;
background-color: rgb(50, 150, 100);
border-radius: 3px;
outline: none;
margin: 1pt;
color: white;
text-align: center;
line-height: 130px;
font-size: 40px;
font-weight: 800;
}
#container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 230px;
height: 200px;
background-color: #aaa;
}
#zanting {
position: absolute;
top: 75%;
left: 15px;
width: 90px;
height: 30px;
background-color: #fff;
text-align: center;
line-height: 30px;
border-radius: 5px;
cursor: pointer;
}
#guiling {
position: absolute;
top: 75%;
right: 15px;
width: 90px;
height: 30px;
background-color: #fff;
text-align: center;
line-height: 30px;
border-radius: 5px;
cursor: pointer;
}
#kaishi {
position: absolute;
left: 50%;
bottom: 0;
transform: translate(-50%);
right: 15px;
width: 90px;
height: 30px;
background-color: rgb(50, 150, 100);
text-align: center;
line-height: 30px;
border-radius: 15px;
cursor: pointer;
color: white;
}
#zanting:hover {
background-color: rgb(230, 230, 230);
}
#guiling:hover {
background-color: rgb(230, 230, 230);
}
#kaishi:hover {
background-color: rgb(39, 126, 83);
}
</style>
</head>
<body>
<div id="container">
<div id="kuai"></div>
<div id="zanting" onclick="stop()">暂停</div>
<div id="guiling" onclick="back()">归零</div>
<div id="kaishi" onclick="start()">开始</div>
</div>
<script>
var flag = false;
var count = 0;
var kuai = document.getElementById('kuai');
kuai.innerHTML = '0.00';
function number() {
if (flag)
{count +=0.01;
var ans = parseInt(count*100)/100;
var newAns = ans.toString();
pos = newAns.indexOf('.');
if (newAns.length - pos < 3) {
newAns += '0';
}
kuai.innerHTML = newAns;}
}
var timer = setInterval(number,10);
function stop() {
flag = false;
}
function back() {
stop()
count = 0;
kuai.innerHTML = '0.00';
}
function start() {
flag = true;
}
</script>
</body>
</html>