用js写一个时钟
时间: 2023-11-27 09:54:13 浏览: 30
好的,以下是一个简单的基于JS的时钟实现:
```html
<!DOCTYPE html>
<html>
<head>
<title>JS Clock</title>
<style>
body {
background-color: #333;
color: #fff;
font-size: 50px;
text-align: center;
}
</style>
</head>
<body>
<h1 id="clock"></h1>
<script>
function updateTime() {
let now = new Date();
let hours = now.getHours().toString().padStart(2, '0');
let minutes = now.getMinutes().toString().padStart(2, '0');
let seconds = now.getSeconds().toString().padStart(2, '0');
document.getElementById('clock').textContent = `${hours}:${minutes}:${seconds}`;
}
setInterval(updateTime, 1000); // 每秒更新一次时间
</script>
</body>
</html>
```
在 `<body>` 中添加一个 `<h1>` 标签,用来显示当前时间。在 `<script>` 中定义一个 `updateTime()` 函数,用来更新时间。使用 `setInterval()` 函数,每秒钟调用一次 `updateTime()` 来更新时间。在 `updateTime()` 函数中,我们使用 `Date` 对象获取当前时间,并将小时、分钟和秒数转换成字符串,使用 `padStart()` 函数来确保它们始终是两位数。最后,我们将时间字符串设置为 `<h1>` 标签的文本内容,以在页面上显示时间。