如何在Sass中检测指定class是否存在并设置差异化样式
实现方案
Sass 内置了 selector-exists() 函数可以直接检测指定选择器是否已被定义,刚好满足你的需求。
你原代码的判断逻辑是将拼接后的选择器字符串和固定字符串 'null' 做比对,该判断永远成立,所以所有生成的图标类都会被设置为紫色,无法达到预期效果。
以下是可直接运行的正确实现:
// 已定义的gg图标类 .gg-spider{ color: red; } .gg-hulk{ color: green; } // 改造后的mixin @mixin iconmixin($glyph, $gg, $after: null){ // 先拼接成完整的gg选择器字符串 $gg-selector: ".gg-#{$gg}"; .glyph-#{$glyph}{ @extend #{$gg-selector} !optional; // 检测gg选择器是否不存在,不存在则设置标识色 @if not selector-exists($gg-selector) { color: purple; } } } // 图标映射关系 $icons: peter spider, bruce hulk, tony iron; // 批量生成类 @each $icon in $icons { @include iconmixin(nth($icon, 1), nth($icon, 2), nth($icon, 3)); }
编译后效果:
.glyph-peter会继承.gg-spider的红色,无紫色样式.glyph-bruce会继承.gg-hulk的绿色,无紫色样式.glyph-tony因为不存在.gg-iron类,会被设置为紫色,符合你快速定位未配置图标的需求
如果使用的Sass版本过低不支持selector-exists(),可以手动维护一个已存在的gg图标名称列表,用index()函数判断:
// 手动维护已存在的gg图标名列表 $exist-gg-list: spider, hulk; @mixin iconmixin($glyph, $gg, $after: null){ .glyph-#{$glyph}{ @extend .gg-#{$gg} !optional; @if not index($exist-gg-list, $gg) { color: purple; } } }
内容的提问来源于stack exchange,提问作者Jason Teunissen
相关产品推荐
相关产品推荐

