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

能否在CSS @keyframes中使用JS设置的CSS变量作为动画起始值?

实现从JS设置的CSS变量起始的时钟动画

完全可行,按以下步骤操作即可:

1. 修正@keyframes语法

你原来的写法存在语法错误,CSS变量和单位的组合需要放在calc()内部,调整后的关键帧如下:

@keyframes move-niddle {
  0% {
    transform: rotate(calc(var(--start) * 1deg));
  }
  100% {
    transform: rotate(calc(var(--start) * 1deg + 360deg));
  }
}

这样动画会从--start对应的角度开始,最终旋转到起始角度+360°的位置,保证循环时指针运动平滑无跳变。

2. 用JS计算并设置起始角度

通过JavaScript获取当前时间,计算时针、分针、秒针对应的初始角度,再将角度值赋值给对应元素的--start CSS变量:

// 获取当前时间
const now = new Date();
const seconds = now.getSeconds();
const minutes = now.getMinutes();
const hours = now.getHours();

// 计算各指针初始角度(每6°对应一分钟/一秒,每30°对应一小时)
const secAngle = seconds * 6;
const minAngle = minutes * 6 + seconds * 0.1; // 分针随秒数微调
const hourAngle = (hours % 12) * 30 + minutes * 0.5 + seconds * (0.5 / 60); // 时针随分、秒微调

// 给各指针元素设置CSS变量
document.querySelector('.second-hand').style.setProperty('--start', secAngle);
document.querySelector('.minute-hand').style.setProperty('--start', minAngle);
document.querySelector('.hour-hand').style.setProperty('--start', hourAngle);

3. 给指针元素配置动画

确保给每个指针元素设置动画属性和旋转原点(指针的底部中心):

.second-hand {
  animation: move-niddle 60s linear infinite;
  transform-origin: bottom center;
}

.minute-hand {
  animation: move-niddle 3600s linear infinite;
  transform-origin: bottom center;
}

.hour-hand {
  animation: move-niddle 43200s linear infinite;
  transform-origin: bottom center;
}

原理说明:

  • CSS变量--start是每个指针的专属初始角度,由JS动态计算当前时间后赋值到元素的行内样式中。
  • @keyframes通过calc()将变量值转换为角度单位,让动画从当前时间对应的位置开始运行,后续自动按周期循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 17:30:11