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

动态修改keyframes后如何重启更新后的动画?

CSS Text-Indent Marquee: Modified Keyframes Aren't Taking Effect

最近我在折腾用**带动画的text-indent**实现跑马灯效果(前期做了大量调研),比起translateX(100%)这类方案,我更偏向这个思路——因为前者很容易出现文本溢出跑马灯容器边界的问题。

我基于一个旧示例做了现代化改造:改用TypeScript实现,用appendRule替代了旧的insertRule API,也不再考虑旧浏览器兼容。但现在碰到个棘手的问题:修改keyframes规则后重启动画,居然还是沿用旧的关键帧配置,注释里写的“重新分配动画以使其运行”这一步完全没起作用。

我已经通过调试器确认规则确实被修改了:旧的0%、100%规则已经删掉,新规则也成功添加,但旧规则好像被浏览器缓存了,怎么都清不掉,动画还是按原来的数值滚动。

我的代码如下:

CSS 代码

#marquee { 
  position: fixed; 
  left: 0; 
  right: 170px; 
  bottom: 0; 
  background-color: midnightblue; 
  font-size: 14px; 
  padding: 2px 1em; 
  overflow: hidden; 
  white-space: nowrap; 
  animation: none; 
} 
#marquee:hover { 
  animation-play-state: paused; 
} 
@keyframes marquee-0 { 
  0% { text-indent: 450px; } 
  100% { text-indent: -500px; } 
} 

TypeScript 代码片段

function updateMarqueeAnimation() { 
  const marqueeRule = getKeyframesRule('marquee-0'); 
  if (!marqueeRule) return; 
  marquee.css('animation', 'unset'); 
  const element = marquee[0]; 
  const textWidth = getTextWidth(marquee.text(), element); 
  const padding = Number(window.getComputedStyle(element).getPropertyValue('padding-left').replace('px', '')) + 
                  Number(window.getComputedStyle(element).getPropertyValue('padding-right').replace('px', '')); 
  const offsetWidth = element.offsetWidth; 
  if (textWidth + padding <= offsetWidth) return; 
  
  marqueeRule.deleteRule('0%'); 
  marqueeRule.deleteRule('100%'); 
  marqueeRule.appendRule('0% { text-indent: ' + offsetWidth + 'px; }'); 
  marqueeRule.appendRule('100% { text-indent: -' + textWidth + 'px; }'); 
  
  setTimeout(() => marquee.css('animation', 'marquee-0 15s linear infinite')); 
} 

我已经尝试过多种解决技巧,比如克隆跑马灯元素并替换原元素,但都无效——动画还是按原样式表的数值运行,导致跑马灯滚动无法适配不同文本宽度。我下一步可能尝试动态创建新的keyframes对象而非编辑现有对象,但这是一种较繁琐的方案,希望能获得更优解。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:45:44