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

CSS动画计数器仅苹果设备无法运行的兼容问题求解

兼容问题根因

Safari浏览器长期不支持在@keyframes规则中修改counter-increment、counter-reset等计数器属性,这是导致原有代码在苹果设备上无法生效的核心原因。

解决方案

方案1:纯CSS实现(兼容Safari 16.4及以上版本)

通过可动画的自定义CSS属性间接控制计数器,绕过Safari的兼容限制,HTML代码无需修改:

/* 声明整数类型的可动画自定义属性 */
@property --count {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}

div::after {
  font: 800 40px system-ui;
  counter-reset: count var(--count);
  content: counter(count);
  animation: counter 5s linear forwards;
}

@keyframes counter {
   0% { --count: 0;    }
  10% { --count: 8;    }
  20% { --count: 16;   }
  30% { --count: 32;   }
  40% { --count: 64;   }
  50% { --count: 128;  }
  60% { --count: 256;  }
  70% { --count: 512;  }
  80% { --count: 1024; }
  90% { --count: 2048; }
 100% { --count: 4000; }
}
<div></div>

该方案适配iOS 16.4+、macOS 13.3+及以上版本的苹果设备,和原有Chrome、Firefox的表现完全一致。

方案2:轻量JS实现(兼容全版本Safari)

如果需要覆盖更旧的苹果设备,可使用JS实现相同效果,无兼容问题:

<div id="counter"></div>
<style>
#counter {
  font: 800 40px system-ui;
}
</style>
<script>
const counterEl = document.getElementById('counter');
// 动画总时长,和原CSS动画的5秒保持一致
const totalDuration = 5000;
const startTime = Date.now();
// 对应原CSS的关键帧数值
const countValues = [0, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4000];

function runCounter() {
  const elapsed = Date.now() - startTime;
  const progress = Math.min(elapsed / totalDuration, 1);
  const currentFrame = Math.min(Math.floor(progress * 10), 10);
  counterEl.textContent = countValues[currentFrame];
  if (progress < 1) {
    requestAnimationFrame(runCounter);
  }
}

requestAnimationFrame(runCounter);
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:36:03