使用 HTML、CSS 和 JavaScript 的简单模拟时钟
warning:
这篇文章距离上次修改已过284天,其中的内容可能已经有所变动。
以下是一个使用HTML、CSS和JavaScript创建的简单模拟时钟示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Clock</title>
<style>
#clock {
width: 300px;
margin: 0 auto;
padding: 20px;
text-align: center;
background-color: #f0f0f0;
border-radius: 10px;
box-shadow: 0 0 5px #ccc;
}
#clock h1 {
font-size: 40px;
color: #555;
}
#clock p {
font-size: 20px;
color: #aaa;
}
</style>
</head>
<body onload="startTime()">
<div id="clock">
<h1 id="hours"></h1>
<h1 id="minutes"></h1>
<h1 id="seconds"></h1>
<p id="am_pm"></p>
</div>
<script>
function startTime() {
const today = new Date();
const hours = today.getHours();
const minutes = today.getMinutes();
const seconds = today.getSeconds();
const am_pm = hours >= 12 ? 'PM' : 'AM';
// update hours
document.getElementById('hours').innerText = formatTime(hours);
// update minutes
document.getElementById('minutes').innerText = formatTime(minutes);
// update seconds
document.getElementById('seconds').innerText = formatTime(seconds);
// update AM/PM
document.getElementById('am_pm').innerText = am_pm;
setTimeout(startTime, 1000);
}
function formatTime(time) {
return time < 10 ? '0' + time : time;
}
</script>
</body>
</html>
这段代码会在网页上显示一个简单的模拟时钟,包括时间、分钟和秒钟,以及上下午标识。时钟每秒更新一次。
评论已关闭