SCSS计数动画在iPhone端无法运行,求原因排查及兼容方案
解决iOS端数字计数动画失效问题及替代CSS方案
一、添加-webkit-前缀修复原有代码
iOS Safari及iOS Chrome基于WebKit内核,目前不支持不带前缀的@property语法,需添加-webkit-前缀做兼容。修改后的SCSS代码如下:
/* 同时声明标准与WebKit前缀版本的自定义属性规则 */ @property --num { syntax: "<integer>"; initial-value: 0; inherits: false; } @-webkit-property --num { syntax: "<integer>"; initial-value: 0; inherits: false; } div { /* 为动画和计数器属性添加-webkit-前缀 */ -webkit-animation: counter 5s infinite alternate ease-in-out; animation: counter 5s infinite alternate ease-in-out; -webkit-counter-reset: num var(--num); counter-reset: num var(--num); font: 800 40px system-ui; padding: 2rem; } div::after { content: counter(num); } /* 同时编写带前缀和标准版本的关键帧 */ @-webkit-keyframes counter { from { --num: 0; } to { --num: 100; } } @keyframes counter { from { --num: 0; } to { --num: 100; } }
核心说明:
- 必须同时声明
@property和@-webkit-property,WebKit内核才能识别自定义属性的动画规则 - 动画、计数器相关属性也需添加
-webkit-前缀,确保iOS端正常解析
二、无需@property的纯CSS计数方案
如果不想依赖@property(部分旧版WebKit可能仍有兼容问题),可以通过以下两种方式实现:
方案1:利用steps()函数结合计数器
div { -webkit-animation: counter 5s infinite alternate steps(100); animation: counter 5s infinite alternate steps(100); -webkit-counter-reset: num 0; counter-reset: num 0; font: 800 40px system-ui; padding: 2rem; } div::after { content: counter(num); } @-webkit-keyframes counter { to { -webkit-counter-reset: num 100; counter-reset: num 100; } } @keyframes counter { to { counter-reset: num 100; } }
原理:将5秒动画拆分为100个均匀步骤,每一步计数器值递增1,通过动画动态修改counter-reset的值实现数字逐帧变化。
方案2:CSS变量+calc()实现
div { --count: 0; -webkit-animation: counter 5s infinite alternate ease-in-out; animation: counter 5s infinite alternate ease-in-out; font: 800 40px system-ui; padding: 2rem; } div::after { /* 用calc强制将浮点型变量转为整数显示 */ content: calc(var(--count) * 1); } @-webkit-keyframes counter { to { --count: 100; } } @keyframes counter { to { --count: 100; } }
注意:该方案依赖浏览器对CSS变量在content中的支持,部分旧版iOS Safari需添加前缀,calc(var(--count)*1)用于确保显示整数。
内容的提问来源于stack exchange,提问作者ollis9190
相关产品推荐
相关产品推荐

