You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript模拟时钟时分显示错误,求排查代码问题

问题排查与修正

错误原因

  1. 角度偏移错误:所有指针的角度计算错误地添加了90deg,但由于指针的transform-origin是top center(旋转中心在时钟中心,指针默认垂直向下延伸),正确的修正应该是减去90deg,才能让0秒/0分/0点时指针指向12点。
  2. 小时制未转换:原代码直接使用24小时制的小时值计算角度,导致12点之后的小时指针位置错误,需要先转换为12小时制。
  3. 初始样式干扰:CSS中给小时、分钟指针设置了默认旋转角度,页面加载初期会显示错误位置,需要初始化时立即调用时间更新函数。

修正后的代码

JavaScript部分

const handHour = document.querySelector("#hour");
const handMin = document.querySelector("#minutes");
const handSec = document.querySelector("#seconds");

function updateClock() {
  const now = new Date();
  
  // 计算秒针角度
  const seconds = now.getSeconds();
  const secondsAngle = ((seconds / 60) * 360) - 90;
  handSec.style.transform = `rotate(${secondsAngle}deg)`;
  
  // 计算分针角度(包含秒针带来的偏移)
  const minutes = now.getMinutes();
  const minutesAngle = ((minutes / 60) * 360) + ((seconds / 60) * 6) - 90;
  handMin.style.transform = `rotate(${minutesAngle}deg)`;
  
  // 计算时针角度(转换为12小时制,包含分针带来的偏移)
  let hours = now.getHours() % 12;
  const hoursAngle = ((hours / 12) * 360) + ((minutes / 60) * 30) - 90;
  handHour.style.transform = `rotate(${hoursAngle}deg)`;
}

// 初始化时钟
updateClock();
// 每秒更新一次
setInterval(updateClock, 1000);

CSS部分(移除默认旋转)

#hour {
  background-color: #e6c384;
  height: 100px;
  width: 8px;
  /* 移除默认的rotate(125deg) */
}

#minutes {
  background-color: #6a9589;
  height: 120px;
  width: 4px;
  /* 移除默认的rotate(255deg) */
}

说明

  • 指针的transform-origin: top center决定了旋转中心在时钟中心,指针默认垂直向下,因此需要减去90度让初始位置指向12点。
  • 转换为12小时制(hours % 12)确保时针在12小时周期内正确转动。
  • 初始化时调用updateClock(),避免页面加载时显示CSS默认的错误角度。

内容的提问来源于stack exchange,提问作者Anna_16

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 11:39:18