js实现数字时钟并且能够根据时刻判断A.M.或P.M.
时间: 2024-05-01 07:19:50 浏览: 8
可以使用JavaScript Date对象来获取当前时间,并使用定时器来更新时钟。
以下是一个简单的示例代码:
HTML:
```html
<!DOCTYPE html>
<html>
<head>
<title>Digital Clock</title>
<style>
.clock {
font-size: 48px;
text-align: center;
}
</style>
</head>
<body>
<div class="clock"></div>
<script src="clock.js"></script>
</body>
</html>
```
JavaScript:
```javascript
function updateClock() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var amPm = hours >= 12 ? 'PM' : 'AM'; // 判断A.M.或P.M.
hours = hours % 12;
hours = hours ? hours : 12; // 处理午夜12点
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
var time = hours + ':' + minutes + ':' + seconds + ' ' + amPm;
document.querySelector('.clock').innerHTML = time;
}
setInterval(updateClock, 1000); // 每秒更新一次时钟
```
这个代码将会在页面上显示一个数字时钟,每秒更新一次。同时,它还会根据当前时间判断A.M.或P.M.。