运用前端技术写出一个计时器代码
<!DOCTYPE html>
<html>
<head>
<title>计时器</title>
<meta charset="utf-8">
<style type="text/css">
.container {
display: flex;
flex-direction: column;
align-items: center;
padding-top: 100px;
}
<pre><code> .timer {
font-size: 50px;
font-weight: bold;
margin-bottom: 50px;
}
.btn {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</code></pre>
</head>
<body>
<div class="container">
<div class="timer">00:00:00</div>
<button class="btn" id="start">开始</button>
<button class="btn" id="stop">停止</button>
<button class="btn" id="reset">重置</button>
</div>
<pre><code><script type="text/javascript">
var hours = 0;
var minutes = 0;
var seconds = 0;
var timer;
function addZero(num) {
if (num < 10) {
return "0" + num;
} else {
return num;
}
}
function startTimer() {
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
}
if (minutes == 60) {
minutes = 0;
hours++;
}
var h = addZero(hours);
var m = addZero(minutes);
var s = addZero(seconds);
document.querySelector(".timer").innerHTML = h + ":" + m + ":" + s;
}
document.getElementById("start").addEventListener("click", function() {
timer = setInterval(startTimer, 1000);
});
document.getElementById("stop").addEventListener("click", function() {
clearInterval(timer);
});
document.getElementById("reset").addEventListener("click", function() {
clearInterval(timer);
hours = 0;
minutes = 0;
seconds = 0;
document.querySelector(".timer").innerHTML = "00:00:00";
});
</script>
</code></pre>
</body>
</html>
原文地址: http://www.cveoy.top/t/topic/Ec8 著作权归作者所有。请勿转载和采集!