当前位置:首页 > JavaScript

js 时钟实现

2026-01-31 20:47:08JavaScript

实现基础数字时钟

使用JavaScript的Date对象获取当前时间,并通过setInterval动态更新显示:

function updateClock() {
  const now = new Date();
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');
  document.getElementById('digital-clock').textContent = `${hours}:${minutes}:${seconds}`;
}

setInterval(updateClock, 1000);
updateClock(); // 立即执行一次避免初始空白

HTML部分需要包含一个显示元素:

<div id="digital-clock"></div>

实现模拟时钟

通过CSS旋转和JavaScript计算角度来实现钟表指针:

function updateAnalogClock() {
  const now = new Date();
  const seconds = now.getSeconds();
  const minutes = now.getMinutes();
  const hours = now.getHours() % 12;

  const secondDegrees = (seconds / 60) * 360;
  const minuteDegrees = (minutes / 60) * 360 + (seconds / 60) * 6;
  const hourDegrees = (hours / 12) * 360 + (minutes / 60) * 30;

  document.querySelector('.second-hand').style.transform = `rotate(${secondDegrees}deg)`;
  document.querySelector('.minute-hand').style.transform = `rotate(${minuteDegrees}deg)`;
  document.querySelector('.hour-hand').style.transform = `rotate(${hourDegrees}deg)`;
}

setInterval(updateAnalogClock, 1000);
updateAnalogClock();

对应CSS样式:

.clock-face {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  position: relative;
  border: 2px solid #333;
}

.hand {
  position: absolute;
  bottom: 50%;
  left: 50%;
  transform-origin: 50% 100%;
}

.hour-hand {
  width: 6px;
  height: 50px;
  background: #333;
}

.minute-hand {
  width: 4px;
  height: 70px;
  background: #666;
}

.second-hand {
  width: 2px;
  height: 80px;
  background: red;
}

HTML结构:

<div class="clock-face">
  <div class="hand hour-hand"></div>
  <div class="hand minute-hand"></div>
  <div class="hand second-hand"></div>
</div>

添加日期显示

扩展数字时钟功能,添加日期显示:

function updateDateTime() {
  const now = new Date();
  const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
  const dateStr = now.toLocaleDateString(undefined, options);
  const timeStr = now.toLocaleTimeString();

  document.getElementById('date').textContent = dateStr;
  document.getElementById('time').textContent = timeStr;
}

setInterval(updateDateTime, 1000);
updateDateTime();

HTML结构:

<div id="date"></div>
<div id="time"></div>

实现世界时钟

展示不同时区的时间:

function updateWorldClocks() {
  const timeZones = ['America/New_York', 'Asia/Tokyo', 'Europe/London'];
  const clocksContainer = document.getElementById('world-clocks');

  clocksContainer.innerHTML = timeZones.map(zone => {
    const time = new Date().toLocaleTimeString('en-US', { 
      timeZone: zone,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
    return `<div class="clock">${zone.split('/')[1]}: ${time}</div>`;
  }).join('');
}

setInterval(updateWorldClocks, 1000);
updateWorldClocks();

性能优化建议

使用requestAnimationFrame替代setInterval可以获得更平滑的动画效果,特别是在实现秒针连续移动时:

function smoothClock() {
  const now = new Date();
  const milliseconds = now.getMilliseconds();
  const seconds = now.getSeconds() + milliseconds / 1000;

  const secondDegrees = (seconds / 60) * 360;
  document.querySelector('.second-hand').style.transform = `rotate(${secondDegrees}deg)`;

  requestAnimationFrame(smoothClock);
}

smoothClock();

添加时钟样式主题

通过CSS变量实现主题切换功能:

function changeTheme(theme) {
  document.documentElement.style.setProperty('--clock-bg', theme.bg);
  document.documentElement.style.setProperty('--clock-text', theme.text);
}

const themes = {
  dark: { bg: '#222', text: '#fff' },
  light: { bg: '#eee', text: '#333' },
  vintage: { bg: '#f5f5dc', text: '#8b4513' }
};

对应CSS:

js 时钟实现

:root {
  --clock-bg: #eee;
  --clock-text: #333;
}

.digital-clock {
  background: var(--clock-bg);
  color: var(--clock-text);
}

标签: 时钟js
分享给朋友:

相关文章

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js实现报表

js实现报表

使用JavaScript实现报表 在JavaScript中实现报表功能可以通过多种方式完成,常见的方法包括使用原生JavaScript、第三方库(如Chart.js、D3.js)或结合后端数据渲染。以…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…

js实现文字滚动

js实现文字滚动

实现文字滚动的几种方法 使用CSS动画实现滚动 通过CSS的@keyframes和transform属性可以实现平滑的文字滚动效果。 <style> .scroll-text { w…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…