SASS @mixin复用异常:参数值重复调用致发光效果错误
问题分析与解决方案:SASS @mixin 动画冲突导致发光颜色统一
嘿,我一眼就揪出你遇到的问题根源啦!
为什么所有图标发光颜色都一样?
你写的@mixin里定义了同名的@keyframes glow,这就是罪魁祸首!
SASS的mixin本质是「代码片段复制粘贴」——当你给.good和.bad分别调用textGlow时,会在编译后的CSS里生成两个完全一样名字的@keyframes glow规则。而CSS是「后定义覆盖先定义」的逻辑,所以最后调用的红色动画会把绿色的给覆盖掉,所有图标自然都变成红色发光了。
怎么解决?给动画加唯一标识就行
我们只需要让每次调用mixin时生成的keyframes名字不重复,有两种简单的方法:
方法1:手动指定动画名(直观可控)
先修改你的_mixins.scss,给mixin加一个可选的动画名参数:
@mixin textGlow($glowColor, $animationName: glow) { @keyframes #{$animationName} { from { text-shadow: 0 0 1px $glowColor, 0 0 2px $glowColor, 0 0 3px $glowColor; } to { text-shadow: 0 0 3px lighten($glowColor, 5%), 0 0 4px lighten($glowColor, 15%), 0 0 5px lighten($glowColor, 30%); } } @-webkit-keyframes #{$animationName} { from { text-shadow: 0 0 1px $glowColor, 0 0 2px $glowColor, 0 0 3px $glowColor; } to { text-shadow: 0 0 3px lighten($glowColor, 5%), 0 0 4px lighten($glowColor, 15%), 0 0 5px lighten($glowColor, 30%); } } -webkit-animation: #{$animationName} 1s ease-in-out infinite alternate; -moz-animation: #{$animationName} 1s ease-in-out infinite alternate; animation: #{$animationName} 1s ease-in-out infinite alternate; }
然后调用的时候给每个图标指定独有的动画名:
@import '../styles/variables'; @import '../styles/mixins'; i.fa-circle.good{ color: $my-green; @include textGlow($my-green, glow-green); } i.fa-circle.bad{ color: $my-red; @include textGlow($my-red, glow-red); }
方法2:自动生成唯一动画名(省心)
如果你不想手动起名,用SASS的unique-id()函数自动生成唯一标识就好,修改后的mixin如下:
@mixin textGlow($glowColor) { // 生成唯一的动画名 $animationName: glow-#{unique-id()}; @keyframes #{$animationName} { from { text-shadow: 0 0 1px $glowColor, 0 0 2px $glowColor, 0 0 3px $glowColor; } to { text-shadow: 0 0 3px lighten($glowColor, 5%), 0 0 4px lighten($glowColor, 15%), 0 0 5px lighten($glowColor, 30%); } } @-webkit-keyframes #{$animationName} { from { text-shadow: 0 0 1px $glowColor, 0 0 2px $glowColor, 0 0 3px $glowColor; } to { text-shadow: 0 0 3px lighten($glowColor, 5%), 0 0 4px lighten($glowColor, 15%), 0 0 5px lighten($glowColor, 30%); } } -webkit-animation: #{$animationName} 1s ease-in-out infinite alternate; -moz-animation: #{$animationName} 1s ease-in-out infinite alternate; animation: #{$animationName} 1s ease-in-out infinite alternate; }
调用的时候直接传颜色就行,完全不用管动画名:
i.fa-circle.good{ color: $my-green; @include textGlow($my-green); } i.fa-circle.bad{ color: $my-red; @include textGlow($my-red); }
关于@mixin的使用场景
放心,这个场景非常适合用@mixin!它本来就是用来复用重复CSS代码的,你之前只是踩了「全局规则命名冲突」的小坑而已,解决之后就能完美发挥它的作用啦。
内容的提问来源于stack exchange,提问作者terahertz
相关产品推荐
相关产品推荐

