js时钟实现
使用Date对象获取时间
通过JavaScript的Date对象可以获取当前时间的小时、分钟和秒数。以下是基本实现代码:
function updateClock() {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
console.log(`${hours}:${minutes}:${seconds}`);
}
定时刷新显示
使用setInterval函数每隔1秒更新一次时间显示:
setInterval(updateClock, 1000);
格式化时间显示
对个位数时间值补零,使显示更规范:
function formatTime(time) {
return time < 10 ? `0${time}` : time;
}
function updateClock() {
const now = new Date();
const hours = formatTime(now.getHours());
const minutes = formatTime(now.getMinutes());
const seconds = formatTime(now.getSeconds());
console.log(`${hours}:${minutes}:${seconds}`);
}
页面显示时钟
将时钟显示在HTML页面上:
<div id="clock"></div>
<script>
function updateClock() {
const now = new Date();
const hours = formatTime(now.getHours());
const minutes = formatTime(now.getMinutes());
const seconds = formatTime(now.getSeconds());
document.getElementById('clock').textContent = `${hours}:${minutes}:${seconds}`;
}
setInterval(updateClock, 1000);
updateClock(); // 立即执行一次避免初始空白
</script>
添加AM/PM显示
实现12小时制并添加AM/PM标识:
function updateClock() {
const now = new Date();
let hours = now.getHours();
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // 0点转换为12
const minutes = formatTime(now.getMinutes());
const seconds = formatTime(now.getSeconds());
document.getElementById('clock').textContent =
`${hours}:${minutes}:${seconds} ${ampm}`;
}
实现数字时钟动画效果
添加CSS样式实现平滑过渡效果:
#clock {
font-family: 'Arial', sans-serif;
font-size: 3em;
color: #333;
transition: all 0.5s ease;
}
添加日期显示
扩展功能显示当前日期:

function updateClock() {
const now = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const dateString = now.toLocaleDateString(undefined, options);
// 原有时间代码...
document.getElementById('date').textContent = dateString;
}






