JavaScript显示一个动态时钟
时间: 2024-05-04 11:20:02 浏览: 13
可以使用JavaScript来实现动态时钟。以下是一个简单的例子:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>Digital Clock</title>
</head>
<body>
<h1 id="clock"></h1>
<script src="clock.js"></script>
</body>
</html>
```
JavaScript代码(保存为clock.js):
```
function showTime() {
var date = new Date(); // 获取当前时间
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
// 将小时、分钟和秒格式化为两位数
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
// 将时间显示在页面上
var clock = document.getElementById("clock");
clock.innerText = hours + ":" + minutes + ":" + seconds;
// 每秒钟更新一次时间
setTimeout(showTime, 1000);
}
showTime(); // 调用showTime函数,开始显示时间
```
这段代码会在页面上显示当前时间,并且每秒钟更新一次。