当前位置:首页 > 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结构:

js 时钟实现

<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>

实现世界时钟

展示不同时区的时间:

js 时钟实现

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:

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

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

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

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

js实现

js实现

实现 JavaScript 功能的方法 在 JavaScript 中实现特定功能通常涉及多个步骤。以下是常见的实现方法: 基础语法和变量声明 使用 let 或 const 声明变量: let co…

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Pa…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js轮播图实现原理

js轮播图实现原理

轮播图的基本原理 轮播图通过动态切换显示的内容(图片、文本等)实现视觉上的滑动效果。核心原理是利用CSS和JavaScript控制元素的显示与隐藏,或通过变换位置实现滑动动画。 实现方法一:CSS…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…