用HTML写一个计时器
时间: 2023-10-12 10:05:12 浏览: 36
以下是一个简单的 HTML 计时器示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>计时器</title>
</head>
<body>
<h1>计时器</h1>
<p>点击“开始”按钮开始计时:</p>
<button onclick="startTimer()">开始</button>
<button onclick="stopTimer()">停止</button>
<p id="timer"></p>
<script>
var seconds = 0;
var timer;
function startTimer() {
timer = setInterval(updateTimer, 1000);
}
function stopTimer() {
clearInterval(timer);
seconds = 0;
document.getElementById("timer").innerHTML = "00:00:00";
}
function updateTimer() {
seconds++;
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor((seconds - (hours * 3600)) / 60);
var remainingSeconds = seconds - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
}
</script>
</body>
</html>
```
这个计时器使用 `setInterval` 函数来每秒更新计时器,然后使用简单的数学运算来将总秒数转换为小时、分钟和秒数。同时,也提供了开始和停止按钮来控制计时器。