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

Chrome下indeterminate progress伪类背景动画失效的兼容方案求助

兼容方案:用伪元素实现动画,保留原生<progress>标签

我之前也踩过Chrome这个UA Shadow作用域的坑,刚好有个不用替换<progress>标签的完美解决方案,既能保留语义化,又能让动画正常跑起来:

实现代码

HTML

<progress max="100"></progress>

CSS

progress {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  border: none;
  position: relative;
  /* 隐藏原生进度条的背景,让伪元素显示 */
  background-color: transparent;
}

/* 针对Chrome/Safari的不确定状态,隐藏原生bar背景 */
progress:not([value])::-webkit-progress-bar {
  background-color: transparent;
}

/* 针对Firefox的不确定状态,隐藏原生进度条背景 */
progress:not([value])::-moz-progress-bar {
  background-color: transparent;
}

/* 用伪元素承载条纹背景和动画 */
progress:not([value])::before {
  content: '';
  position: absolute;
  inset: 0; /* 等价于top/right/bottom/left:0 */
  background-image: 
    linear-gradient(-45deg, transparent 33%, rgba(0,0,0,0.2) 33%, rgba(0,0,0,0.2) 66%, transparent 66%),
    linear-gradient(#b3ee3a, #b3ee3a);
  background-size: 2.5em 1.25em, 100% 100%;
  animation: stripes 2s linear infinite;
}

/* 文档作用域内的关键帧,伪元素可以正常访问 */
@keyframes stripes {
  from { background-position: 0% 0; }
  to { background-position: 100% 0; }
}

原理说明

这个方案的核心是绕开UA Shadow Root的作用域限制:

  • 不再尝试给Chrome内置的::-webkit-progress-bar(属于UA Shadow Root)绑定动画,而是在原生<progress>元素上添加一个::before伪元素
  • 伪元素属于文档作用域,所以文档里定义的@keyframes可以正常被它识别,动画自然就能运行
  • 我们把原生进度条的背景设为透明,让伪元素的条纹背景完全覆盖,视觉效果和你最初的需求完全一致

兼容性

这个方法在Chrome、Firefox、Safari等主流浏览器都能正常工作,既保留了<progress>的语义化优势,又解决了动画失效的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:08:33