1. HTML结构
首先,我们需要定义一个简单的HTML结构来展示时钟和计时器。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>时钟与计时器</title>
<link rel="stylesheet" href="style.css"> <!-- 如果有CSS样式 -->
</head>
<body>
<div id="clock"></div>
<div id="timer">00:00:00</div>
<button id="startTimer">开始计时</button>
<button id="stopTimer">停止计时</button>
<script src="script.js"></script>
</body>
</html>
2. CSS样式(可选)
接着,你可以为这些元素添加一些基本的样式以改善外观。
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
#clock, #timer {
font-size: 2em;
margin: 10px;
}
3. JavaScript实现
最后,我们使用JavaScript来实现时钟的实时更新和计时器的功能。
// 实时更新时钟
function updateClock() {
const now = new Date();
const clockElement = document.getElementById('clock');
clockElement.textContent = now.toLocaleTimeString();
}
setInterval(updateClock, 1000); // 每秒更新时间
// 计时器功能
let timerInterval = null;
let elapsedTime = 0; // 经过的时间,单位为秒
function startTimer() {
if (timerInterval !== null) return; // 防止重复启动
timerInterval = setInterval(() => {
elapsedTime++;
const hours = Math.floor(elapsedTime / 3600).toString().padStart(2, '0');
const minutes = Math.floor((elapsedTime % 3600) / 60).toString().padStart(2, '0');
const seconds = (elapsedTime % 60).toString().padStart(2, '0');
document.getElementById('timer').textContent = `${hours}:${minutes}:${seconds}`;
}, 1000);
}
function stopTimer() {
clearInterval(timerInterval);
timerInterval = null;
}
document.getElementById('startTimer').addEventListener('click', startTimer);
document.getElementById('stopTimer').addEventListener('click', stopTimer);